blob: 365e6a23b5c5ac40290a075824bcb1d0dd625328 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner29375652006-12-04 18:06:35 +00006//
7//===----------------------------------------------------------------------===//
James Dennett84053fb2012-06-22 05:14:59 +00008///
9/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010/// Implements semantic analysis for C++ expressions.
James Dennett84053fb2012-06-22 05:14:59 +000011///
12//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000013
Saar Raza0f50d72020-01-18 09:11:43 +020014#include "clang/Sema/Template.h"
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.
Gauthier Harnischef629c72019-06-14 08:25:52 +000094 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
Richard Smith69bc9aa2018-06-22 19:50:19 +000095 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.
Richard Smith0e3a4872020-02-07 16:34:08 -0800159 //
160 // For now, we accept all the cases in which the name given could plausibly
161 // be interpreted as a correct destructor name, issuing off-by-default
162 // extension diagnostics on the cases that don't strictly conform to the
163 // C++20 rules. This basically means we always consider looking in the
164 // nested-name-specifier prefix, the complete nested-name-specifier, and
165 // the scope, and accept if we find the expected type in any of the three
166 // places.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000167
Richard Smith64e033f2015-01-15 00:48:52 +0000168 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000169 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000170
Richard Smith0e3a4872020-02-07 16:34:08 -0800171 // Whether we've failed with a diagnostic already.
172 bool Failed = false;
173
174 llvm::SmallVector<NamedDecl*, 8> FoundDecls;
175 llvm::SmallSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
176
Douglas Gregorfe17d252010-02-16 19:09:40 +0000177 // If we have an object type, it's because we are in a
178 // pseudo-destructor-expression or a member access expression, and
179 // we know what type we're looking for.
Richard Smith0e3a4872020-02-07 16:34:08 -0800180 QualType SearchType =
181 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000182
Richard Smith0e3a4872020-02-07 16:34:08 -0800183 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
Richard Smith98ed0c52020-02-26 14:50:04 -0800184 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
185 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
186 if (!Type)
187 return false;
Richard Smith0e3a4872020-02-07 16:34:08 -0800188
Richard Smith98ed0c52020-02-26 14:50:04 -0800189 if (SearchType.isNull() || SearchType->isDependentType())
190 return true;
191
192 QualType T = Context.getTypeDeclType(Type);
193 return Context.hasSameUnqualifiedType(T, SearchType);
194 };
195
196 unsigned NumAcceptableResults = 0;
Richard Smith0e3a4872020-02-07 16:34:08 -0800197 for (NamedDecl *D : Found) {
Richard Smith98ed0c52020-02-26 14:50:04 -0800198 if (IsAcceptableResult(D))
199 ++NumAcceptableResults;
200
Richard Smith0e3a4872020-02-07 16:34:08 -0800201 // Don't list a class twice in the lookup failure diagnostic if it's
202 // found by both its injected-class-name and by the name in the enclosing
203 // scope.
204 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
205 if (RD->isInjectedClassName())
206 D = cast<NamedDecl>(RD->getParent());
207
208 if (FoundDeclSet.insert(D).second)
209 FoundDecls.push_back(D);
210 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000211
Richard Smith98ed0c52020-02-26 14:50:04 -0800212 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
213 // results, and all non-matching results if we have a search type. It's not
214 // clear what the right behavior is if destructor lookup hits an ambiguity,
215 // but other compilers do generally accept at least some kinds of
216 // ambiguity.
217 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
218 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
219 LookupResult::Filter F = Found.makeFilter();
220 while (F.hasNext()) {
221 NamedDecl *D = F.next();
222 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
223 Diag(D->getLocation(), diag::note_destructor_type_here)
224 << Context.getTypeDeclType(TD);
225 else
226 Diag(D->getLocation(), diag::note_destructor_nontype_here);
227
228 if (!IsAcceptableResult(D))
229 F.erase();
230 }
231 F.done();
232 }
233
234 if (Found.isAmbiguous())
235 Failed = true;
236
Douglas Gregorfe17d252010-02-16 19:09:40 +0000237 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
Richard Smith98ed0c52020-02-26 14:50:04 -0800238 if (IsAcceptableResult(Type)) {
239 QualType T = Context.getTypeDeclType(Type);
Richard Smith76f888d2020-02-10 02:17:43 -0800240 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smithc278c002014-01-22 00:30:17 +0000241 return CreateParsedType(T,
242 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000243 }
244 }
245
Richard Smith0e3a4872020-02-07 16:34:08 -0800246 return nullptr;
247 };
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000248
Richard Smith0e3a4872020-02-07 16:34:08 -0800249 bool IsDependent = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000250
Richard Smith0e3a4872020-02-07 16:34:08 -0800251 auto LookupInObjectType = [&]() -> ParsedType {
252 if (Failed || SearchType.isNull())
253 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000254
Richard Smith0e3a4872020-02-07 16:34:08 -0800255 IsDependent |= SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000256
Richard Smith76f888d2020-02-10 02:17:43 -0800257 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
Richard Smith0e3a4872020-02-07 16:34:08 -0800258 DeclContext *LookupCtx = computeDeclContext(SearchType);
259 if (!LookupCtx)
260 return nullptr;
261 LookupQualifiedName(Found, LookupCtx);
262 return CheckLookupResult(Found);
263 };
Douglas Gregorfe17d252010-02-16 19:09:40 +0000264
Richard Smith0e3a4872020-02-07 16:34:08 -0800265 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
266 if (Failed)
267 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000268
Richard Smith0e3a4872020-02-07 16:34:08 -0800269 IsDependent |= isDependentScopeSpecifier(LookupSS);
270 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
271 if (!LookupCtx)
272 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000273
Richard Smith76f888d2020-02-10 02:17:43 -0800274 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
Richard Smith0e3a4872020-02-07 16:34:08 -0800275 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
276 Failed = true;
277 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000278 }
Richard Smith0e3a4872020-02-07 16:34:08 -0800279 LookupQualifiedName(Found, LookupCtx);
280 return CheckLookupResult(Found);
281 };
282
283 auto LookupInScope = [&]() -> ParsedType {
284 if (Failed || !S)
285 return nullptr;
286
Richard Smith76f888d2020-02-10 02:17:43 -0800287 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
Richard Smith0e3a4872020-02-07 16:34:08 -0800288 LookupName(Found, S);
289 return CheckLookupResult(Found);
290 };
291
292 // C++2a [basic.lookup.qual]p6:
293 // In a qualified-id of the form
294 //
295 // nested-name-specifier[opt] type-name :: ~ type-name
296 //
297 // the second type-name is looked up in the same scope as the first.
298 //
299 // We interpret this as meaning that if you do a dual-scope lookup for the
300 // first name, you also do a dual-scope lookup for the second name, per
301 // C++ [basic.lookup.classref]p4:
302 //
303 // If the id-expression in a class member access is a qualified-id of the
304 // form
305 //
306 // class-name-or-namespace-name :: ...
307 //
308 // the class-name-or-namespace-name following the . or -> is first looked
309 // up in the class of the object expression and the name, if found, is used.
310 // Otherwise, it is looked up in the context of the entire
311 // postfix-expression.
312 //
313 // This looks in the same scopes as for an unqualified destructor name:
314 //
315 // C++ [basic.lookup.classref]p3:
316 // If the unqualified-id is ~ type-name, the type-name is looked up
317 // in the context of the entire postfix-expression. If the type T
318 // of the object expression is of a class type C, the type-name is
319 // also looked up in the scope of class C. At least one of the
320 // lookups shall find a name that refers to cv T.
321 //
322 // FIXME: The intent is unclear here. Should type-name::~type-name look in
323 // the scope anyway if it finds a non-matching name declared in the class?
324 // If both lookups succeed and find a dependent result, which result should
325 // we retain? (Same question for p->~type-name().)
326
327 if (NestedNameSpecifier *Prefix =
328 SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
329 // This is
330 //
331 // nested-name-specifier type-name :: ~ type-name
332 //
333 // Look for the second type-name in the nested-name-specifier.
334 CXXScopeSpec PrefixSS;
335 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
336 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
337 return T;
338 } else {
339 // This is one of
340 //
341 // type-name :: ~ type-name
342 // ~ type-name
343 //
344 // Look in the scope and (if any) the object type.
345 if (ParsedType T = LookupInScope())
346 return T;
347 if (ParsedType T = LookupInObjectType())
348 return T;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000349 }
350
Richard Smith0e3a4872020-02-07 16:34:08 -0800351 if (Failed)
352 return nullptr;
353
354 if (IsDependent) {
355 // We didn't find our type, but that's OK: it's dependent anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000356
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000357 // FIXME: What if we have no nested-name-specifier?
358 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
359 SS.getWithLocInContext(Context),
360 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000361 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000362 }
363
Richard Smith0e3a4872020-02-07 16:34:08 -0800364 // The remaining cases are all non-standard extensions imitating the behavior
365 // of various other compilers.
366 unsigned NumNonExtensionDecls = FoundDecls.size();
367
368 if (SS.isSet()) {
369 // For compatibility with older broken C++ rules and existing code,
370 //
371 // nested-name-specifier :: ~ type-name
372 //
373 // also looks for type-name within the nested-name-specifier.
374 if (ParsedType T = LookupInNestedNameSpec(SS)) {
375 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
376 << SS.getRange()
377 << FixItHint::CreateInsertion(SS.getEndLoc(),
378 ("::" + II.getName()).str());
379 return T;
David Blaikie5e026f52013-03-20 17:42:13 +0000380 }
Richard Smith0e3a4872020-02-07 16:34:08 -0800381
382 // For compatibility with other compilers and older versions of Clang,
383 //
384 // nested-name-specifier type-name :: ~ type-name
385 //
386 // also looks for type-name in the scope. Unfortunately, we can't
387 // reasonably apply this fallback for dependent nested-name-specifiers.
388 if (SS.getScopeRep()->getPrefix()) {
389 if (ParsedType T = LookupInScope()) {
390 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
391 << FixItHint::CreateRemoval(SS.getRange());
392 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
393 << GetTypeFromParser(T);
394 return T;
395 }
396 }
397 }
398
399 // We didn't find anything matching; tell the user what we did find (if
400 // anything).
401
402 // Don't tell the user about declarations we shouldn't have found.
403 FoundDecls.resize(NumNonExtensionDecls);
404
405 // List types before non-types.
406 std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
407 [](NamedDecl *A, NamedDecl *B) {
408 return isa<TypeDecl>(A->getUnderlyingDecl()) >
409 isa<TypeDecl>(B->getUnderlyingDecl());
410 });
411
412 // Suggest a fixit to properly name the destroyed type.
413 auto MakeFixItHint = [&]{
414 const CXXRecordDecl *Destroyed = nullptr;
415 // FIXME: If we have a scope specifier, suggest its last component?
416 if (!SearchType.isNull())
417 Destroyed = SearchType->getAsCXXRecordDecl();
418 else if (S)
419 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
420 if (Destroyed)
421 return FixItHint::CreateReplacement(SourceRange(NameLoc),
422 Destroyed->getNameAsString());
423 return FixItHint();
424 };
425
426 if (FoundDecls.empty()) {
427 // FIXME: Attempt typo-correction?
428 Diag(NameLoc, diag::err_undeclared_destructor_name)
429 << &II << MakeFixItHint();
430 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
431 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
432 assert(!SearchType.isNull() &&
433 "should only reject a type result if we have a search type");
434 QualType T = Context.getTypeDeclType(TD);
435 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
436 << T << SearchType << MakeFixItHint();
437 } else {
438 Diag(NameLoc, diag::err_destructor_expr_nontype)
439 << &II << MakeFixItHint();
440 }
441 } else {
442 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
443 : diag::err_destructor_expr_mismatch)
444 << &II << SearchType << MakeFixItHint();
445 }
446
447 for (NamedDecl *FoundD : FoundDecls) {
448 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
449 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
450 << Context.getTypeDeclType(TD);
451 else
452 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
453 << FoundD;
David Blaikie5e026f52013-03-20 17:42:13 +0000454 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000455
David Blaikieefdccaa2016-01-15 23:43:34 +0000456 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000457}
458
Richard Smithef2cd8f2017-02-08 20:39:08 +0000459ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
460 ParsedType ObjectType) {
461 if (DS.getTypeSpecType() == DeclSpec::TST_error)
462 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000463
Richard Smithef2cd8f2017-02-08 20:39:08 +0000464 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
465 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
466 return nullptr;
467 }
468
469 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
470 "unexpected type in getDestructorType");
471 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
472
473 // If we know the type of the object, check that the correct destructor
474 // type was named now; we can give better diagnostics this way.
475 QualType SearchType = GetTypeFromParser(ObjectType);
476 if (!SearchType.isNull() && !SearchType->isDependentType() &&
477 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000478 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
479 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000480 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000481 }
482
483 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000484}
485
Richard Smithd091dc12013-12-05 00:58:33 +0000486bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
487 const UnqualifiedId &Name) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000488 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
Richard Smithd091dc12013-12-05 00:58:33 +0000489
490 if (!SS.isValid())
491 return false;
492
493 switch (SS.getScopeRep()->getKind()) {
494 case NestedNameSpecifier::Identifier:
495 case NestedNameSpecifier::TypeSpec:
496 case NestedNameSpecifier::TypeSpecWithTemplate:
497 // Per C++11 [over.literal]p2, literal operators can only be declared at
498 // namespace scope. Therefore, this unqualified-id cannot name anything.
499 // Reject it early, because we have no AST representation for this in the
500 // case where the scope is dependent.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000501 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
502 << SS.getScopeRep();
Richard Smithd091dc12013-12-05 00:58:33 +0000503 return true;
504
505 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000506 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000507 case NestedNameSpecifier::Namespace:
508 case NestedNameSpecifier::NamespaceAlias:
509 return false;
510 }
511
512 llvm_unreachable("unknown nested name specifier kind");
513}
514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000515/// Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000516ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000517 SourceLocation TypeidLoc,
518 TypeSourceInfo *Operand,
519 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000520 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000521 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000522 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000523 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000524 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000525 Qualifiers Quals;
526 QualType T
527 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
528 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000529 if (T->getAs<RecordType>() &&
530 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
531 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000532
David Majnemer6f3150a2014-11-21 21:09:12 +0000533 if (T->isVariablyModifiedType())
534 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
535
Richard Smith5d96b4c2019-10-03 18:55:23 +0000536 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
537 return ExprError();
538
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000539 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
540 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000541}
542
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000543/// Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000544ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000545 SourceLocation TypeidLoc,
546 Expr *E,
547 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000548 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000549 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000550 if (E->getType()->isPlaceholderType()) {
551 ExprResult result = CheckPlaceholderExpr(E);
552 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000553 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000554 }
555
Douglas Gregor9da64192010-04-26 22:37:10 +0000556 QualType T = E->getType();
557 if (const RecordType *RecordT = T->getAs<RecordType>()) {
558 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
559 // C++ [expr.typeid]p3:
560 // [...] If the type of the expression is a class type, the class
561 // shall be completely-defined.
562 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
563 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Douglas Gregor9da64192010-04-26 22:37:10 +0000565 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000566 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000567 // polymorphic class type [...] [the] expression is an unevaluated
568 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000569 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000570 // The subexpression is potentially evaluated; switch the context
571 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000572 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000573 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000574 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000575
576 // We require a vtable to query the type at run time.
577 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000578 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000579 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Richard Smith4a6861a2019-10-09 02:04:54 +0000582 ExprResult Result = CheckUnevaluatedOperand(E);
583 if (Result.isInvalid())
584 return ExprError();
585 E = Result.get();
586
Douglas Gregor9da64192010-04-26 22:37:10 +0000587 // C++ [expr.typeid]p4:
588 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589 // cv-qualified type, the result of the typeid expression refers to a
590 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000591 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000592 Qualifiers Quals;
593 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
594 if (!Context.hasSameType(T, UnqualT)) {
595 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000596 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000597 }
598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
David Majnemer6f3150a2014-11-21 21:09:12 +0000600 if (E->getType()->isVariablyModifiedType())
601 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
602 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000603 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000604 E->HasSideEffects(Context, WasEvaluated)) {
605 // The expression operand for typeid is in an unevaluated expression
606 // context, so side effects could result in unintended consequences.
607 Diag(E->getExprLoc(), WasEvaluated
608 ? diag::warn_side_effects_typeid
609 : diag::warn_side_effects_unevaluated_context);
610 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000611
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000612 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
613 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000614}
615
616/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000617ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000618Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
619 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Anastasia Stulova46b55fa2019-07-18 10:02:35 +0000620 // typeid is not supported in OpenCL.
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000621 if (getLangOpts().OpenCLCPlusPlus) {
622 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
623 << "typeid");
624 }
625
Douglas Gregor9da64192010-04-26 22:37:10 +0000626 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000627 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000628 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000629
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000630 if (!CXXTypeInfoDecl) {
631 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
632 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
633 LookupQualifiedName(R, getStdNamespace());
634 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000635 // Microsoft's typeinfo doesn't have type_info in std but in the global
636 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000637 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000638 LookupQualifiedName(R, Context.getTranslationUnitDecl());
639 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
640 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000641 if (!CXXTypeInfoDecl)
642 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
643 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000644
Nico Weber1b7f39d2012-05-20 01:27:21 +0000645 if (!getLangOpts().RTTI) {
646 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
647 }
648
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000649 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000650
Douglas Gregor9da64192010-04-26 22:37:10 +0000651 if (isType) {
652 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000653 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000654 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
655 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000656 if (T.isNull())
657 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658
Douglas Gregor9da64192010-04-26 22:37:10 +0000659 if (!TInfo)
660 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000661
Douglas Gregor9da64192010-04-26 22:37:10 +0000662 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000663 }
Mike Stump11289f42009-09-09 15:08:12 +0000664
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000666 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000667}
668
David Majnemer1dbc7a72016-03-27 04:46:07 +0000669/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
670/// a single GUID.
671static void
672getUuidAttrOfType(Sema &SemaRef, QualType QT,
673 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
674 // Optionally remove one level of pointer, reference or array indirection.
675 const Type *Ty = QT.getTypePtr();
676 if (QT->isPointerType() || QT->isReferenceType())
677 Ty = QT->getPointeeType().getTypePtr();
678 else if (QT->isArrayType())
679 Ty = Ty->getBaseElementTypeUnsafe();
680
Reid Klecknere516eab2016-12-13 18:58:09 +0000681 const auto *TD = Ty->getAsTagDecl();
682 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000683 return;
684
Reid Klecknere516eab2016-12-13 18:58:09 +0000685 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000686 UuidAttrs.insert(Uuid);
687 return;
688 }
689
690 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000691 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000692 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
693 for (const TemplateArgument &TA : TAL.asArray()) {
694 const UuidAttr *UuidForTA = nullptr;
695 if (TA.getKind() == TemplateArgument::Type)
696 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
697 else if (TA.getKind() == TemplateArgument::Declaration)
698 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
699
700 if (UuidForTA)
701 UuidAttrs.insert(UuidForTA);
702 }
703 }
704}
705
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000706/// Build a Microsoft __uuidof expression with a type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000707ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
708 SourceLocation TypeidLoc,
709 TypeSourceInfo *Operand,
710 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000711 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000712 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000713 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
714 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
715 if (UuidAttrs.empty())
716 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
717 if (UuidAttrs.size() > 1)
718 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000719 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721
David Majnemer2041b462016-03-28 03:19:50 +0000722 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000723 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000724}
725
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000726/// Build a Microsoft __uuidof expression with an expression operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000727ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
728 SourceLocation TypeidLoc,
729 Expr *E,
730 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000731 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000732 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000733 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
734 UuidStr = "00000000-0000-0000-0000-000000000000";
735 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000736 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
737 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
738 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000739 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000740 if (UuidAttrs.size() > 1)
741 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000742 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000743 }
Francois Pichetb7577652010-12-27 01:32:00 +0000744 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000745
David Majnemer2041b462016-03-28 03:19:50 +0000746 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000747 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000748}
749
750/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
751ExprResult
752Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
753 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000754 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000755 if (!MSVCGuidDecl) {
756 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
757 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
758 LookupQualifiedName(R, Context.getTranslationUnitDecl());
759 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
760 if (!MSVCGuidDecl)
761 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762 }
763
Francois Pichet9f4f2072010-09-08 12:20:18 +0000764 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765
Francois Pichet9f4f2072010-09-08 12:20:18 +0000766 if (isType) {
767 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000768 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000769 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
770 &TInfo);
771 if (T.isNull())
772 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773
Francois Pichet9f4f2072010-09-08 12:20:18 +0000774 if (!TInfo)
775 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
776
777 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
778 }
779
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000781 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
782}
783
Steve Naroff66356bd2007-09-16 14:56:35 +0000784/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000785ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000786Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000787 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000788 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000789 return new (Context)
790 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000791}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000792
Sebastian Redl576fd422009-05-10 18:38:11 +0000793/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000794ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000795Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000796 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000797}
798
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000799/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000800ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000801Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
802 bool IsThrownVarInScope = false;
803 if (Ex) {
804 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000805 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000806 // copy/move construction of a class object [...]
807 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000808 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000809 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000810 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000811 // innermost enclosing try-block (if there is one), the copy/move
812 // operation from the operand to the exception object (15.1) can be
813 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000814 // exception object
815 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
816 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
817 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
818 for( ; S; S = S->getParent()) {
819 if (S->isDeclScope(Var)) {
820 IsThrownVarInScope = true;
821 break;
822 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000823
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000824 if (S->getFlags() &
825 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
826 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
827 Scope::TryScope))
828 break;
829 }
830 }
831 }
832 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000833
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000834 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
835}
836
Simon Pilgrim75c26882016-09-30 14:25:09 +0000837ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000838 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000839 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000840 if (!getLangOpts().CXXExceptions &&
Alexey Bataev3167b302019-02-22 14:42:48 +0000841 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
Alexey Bataevc416e642019-02-08 18:02:25 +0000842 // Delay error emission for the OpenMP device code.
Alexey Bataev7feae052019-02-20 19:37:17 +0000843 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexey Bataevc416e642019-02-08 18:02:25 +0000844 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000845
Justin Lebar2a8db342016-09-28 22:45:54 +0000846 // Exceptions aren't allowed in CUDA device code.
847 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000848 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
849 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000850
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000851 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
852 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
853
John Wiegley01296292011-04-08 18:41:53 +0000854 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000855 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
856 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000857 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000858
859 // Initialize the exception result. This implicitly weeds out
860 // abstract types or types with inaccessible copy constructors.
861
862 // C++0x [class.copymove]p31:
863 // When certain criteria are met, an implementation is allowed to omit the
864 // copy/move construction of a class object [...]
865 //
866 // - in a throw-expression, when the operand is the name of a
867 // non-volatile automatic object (other than a function or
868 // catch-clause
869 // parameter) whose scope does not extend beyond the end of the
870 // innermost enclosing try-block (if there is one), the copy/move
871 // operation from the operand to the exception object (15.1) can be
872 // omitted by constructing the automatic object directly into the
873 // exception object
874 const VarDecl *NRVOVariable = nullptr;
875 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000876 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000877
878 InitializedEntity Entity = InitializedEntity::InitializeException(
879 OpLoc, ExceptionObjectTy,
880 /*NRVO=*/NRVOVariable != nullptr);
881 ExprResult Res = PerformMoveOrCopyInitialization(
882 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
883 if (Res.isInvalid())
884 return ExprError();
885 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000886 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000887
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000888 return new (Context)
889 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000890}
891
David Majnemere7a818f2015-03-06 18:53:55 +0000892static void
893collectPublicBases(CXXRecordDecl *RD,
894 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
895 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
896 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
897 bool ParentIsPublic) {
898 for (const CXXBaseSpecifier &BS : RD->bases()) {
899 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
900 bool NewSubobject;
901 // Virtual bases constitute the same subobject. Non-virtual bases are
902 // always distinct subobjects.
903 if (BS.isVirtual())
904 NewSubobject = VBases.insert(BaseDecl).second;
905 else
906 NewSubobject = true;
907
908 if (NewSubobject)
909 ++SubobjectsSeen[BaseDecl];
910
911 // Only add subobjects which have public access throughout the entire chain.
912 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
913 if (PublicPath)
914 PublicSubobjectsSeen.insert(BaseDecl);
915
916 // Recurse on to each base subobject.
917 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
918 PublicPath);
919 }
920}
921
922static void getUnambiguousPublicSubobjects(
923 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
924 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
925 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
926 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
927 SubobjectsSeen[RD] = 1;
928 PublicSubobjectsSeen.insert(RD);
929 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
930 /*ParentIsPublic=*/true);
931
932 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
933 // Skip ambiguous objects.
934 if (SubobjectsSeen[PublicSubobject] > 1)
935 continue;
936
937 Objects.push_back(PublicSubobject);
938 }
939}
940
Sebastian Redl4de47b42009-04-27 20:27:31 +0000941/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000942bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
943 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000944 // If the type of the exception would be an incomplete type or a pointer
945 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000946 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000947 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000948 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000949 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000950 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000951 }
952 if (!isPointer || !Ty->isVoidType()) {
953 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000954 isPointer ? diag::err_throw_incomplete_ptr
955 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000956 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000957 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000958
Richard Sandifordc47f9712020-03-03 10:45:45 +0000959 if (!isPointer && Ty->isSizelessType()) {
960 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
961 return true;
962 }
963
David Majnemerd09a51c2015-03-03 01:50:05 +0000964 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000965 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000966 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000967 }
968
Eli Friedman91a3d272010-06-03 20:39:03 +0000969 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000970 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
971 if (!RD)
972 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000973
Douglas Gregor88d292c2010-05-13 16:44:06 +0000974 // If we are throwing a polymorphic class type or pointer thereof,
975 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000976 MarkVTableUsed(ThrowLoc, RD);
977
Eli Friedman36ebbec2010-10-12 20:32:36 +0000978 // If a pointer is thrown, the referenced object will not be destroyed.
979 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000980 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000981
Richard Smitheec915d62012-02-18 04:13:32 +0000982 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000983 if (!RD->hasIrrelevantDestructor()) {
984 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
985 MarkFunctionReferenced(E->getExprLoc(), Destructor);
986 CheckDestructorAccess(E->getExprLoc(), Destructor,
987 PDiag(diag::err_access_dtor_exception) << Ty);
988 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000989 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000990 }
991 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000992
David Majnemerdfa6d202015-03-11 18:36:39 +0000993 // The MSVC ABI creates a list of all types which can catch the exception
994 // object. This list also references the appropriate copy constructor to call
995 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000996 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000997 // We are only interested in the public, unambiguous bases contained within
998 // the exception object. Bases which are ambiguous or otherwise
999 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +00001000 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1001 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +00001002
David Majnemere7a818f2015-03-06 18:53:55 +00001003 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +00001004 // Attempt to lookup the copy constructor. Various pieces of machinery
1005 // will spring into action, like template instantiation, which means this
1006 // cannot be a simple walk of the class's decls. Instead, we must perform
1007 // lookup and overload resolution.
1008 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
Reid Kleckner812bdb32019-10-30 14:38:11 -07001009 if (!CD || CD->isDeleted())
David Majnemerdfa6d202015-03-11 18:36:39 +00001010 continue;
1011
1012 // Mark the constructor referenced as it is used by this throw expression.
1013 MarkFunctionReferenced(E->getExprLoc(), CD);
1014
1015 // Skip this copy constructor if it is trivial, we don't need to record it
1016 // in the catchable type data.
1017 if (CD->isTrivial())
1018 continue;
1019
1020 // The copy constructor is non-trivial, create a mapping from this class
1021 // type to this constructor.
1022 // N.B. The selection of copy constructor is not sensitive to this
1023 // particular throw-site. Lookup will be performed at the catch-site to
1024 // ensure that the copy constructor is, in fact, accessible (via
1025 // friendship or any other means).
1026 Context.addCopyConstructorForExceptionObject(Subobject, CD);
1027
1028 // We don't keep the instantiated default argument expressions around so
1029 // we must rebuild them here.
1030 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +00001031 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1032 return true;
David Majnemere7a818f2015-03-06 18:53:55 +00001033 }
1034 }
1035 }
Eli Friedman91a3d272010-06-03 20:39:03 +00001036
Akira Hatanakac39a2432019-05-10 02:16:37 +00001037 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1038 // the runtime with no ability for the compiler to request additional
1039 // alignment. Warn if the exception type requires alignment beyond the minimum
1040 // guaranteed by the target C++ runtime.
1041 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1042 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1043 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1044 if (ExnObjAlign < TypeAlign) {
1045 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1046 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1047 << Ty << (unsigned)TypeAlign.getQuantity()
1048 << (unsigned)ExnObjAlign.getQuantity();
1049 }
1050 }
1051
David Majnemerba3e5ec2015-03-13 18:26:17 +00001052 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001053}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001054
Faisal Vali67b04462016-06-11 16:41:54 +00001055static QualType adjustCVQualifiersForCXXThisWithinLambda(
1056 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1057 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1058
1059 QualType ClassType = ThisTy->getPointeeType();
1060 LambdaScopeInfo *CurLSI = nullptr;
1061 DeclContext *CurDC = CurSemaContext;
1062
1063 // Iterate through the stack of lambdas starting from the innermost lambda to
1064 // the outermost lambda, checking if '*this' is ever captured by copy - since
1065 // that could change the cv-qualifiers of the '*this' object.
1066 // The object referred to by '*this' starts out with the cv-qualifiers of its
1067 // member function. We then start with the innermost lambda and iterate
1068 // outward checking to see if any lambda performs a by-copy capture of '*this'
1069 // - and if so, any nested lambda must respect the 'constness' of that
1070 // capturing lamdbda's call operator.
1071 //
1072
Faisal Vali999f27e2017-05-02 20:56:34 +00001073 // Since the FunctionScopeInfo stack is representative of the lexical
1074 // nesting of the lambda expressions during initial parsing (and is the best
1075 // place for querying information about captures about lambdas that are
1076 // partially processed) and perhaps during instantiation of function templates
1077 // that contain lambda expressions that need to be transformed BUT not
1078 // necessarily during instantiation of a nested generic lambda's function call
1079 // operator (which might even be instantiated at the end of the TU) - at which
1080 // time the DeclContext tree is mature enough to query capture information
1081 // reliably - we use a two pronged approach to walk through all the lexically
1082 // enclosing lambda expressions:
1083 //
1084 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1085 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1086 // enclosed by the call-operator of the LSI below it on the stack (while
1087 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1088 // the stack represents the innermost lambda.
1089 //
1090 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1091 // represents a lambda's call operator. If it does, we must be instantiating
1092 // a generic lambda's call operator (represented by the Current LSI, and
1093 // should be the only scenario where an inconsistency between the LSI and the
1094 // DeclContext should occur), so climb out the DeclContexts if they
1095 // represent lambdas, while querying the corresponding closure types
1096 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +00001097
Faisal Vali999f27e2017-05-02 20:56:34 +00001098 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +00001099 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +00001100 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1101 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1102 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +00001103 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1104 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001105
1106 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +00001107 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001108
Faisal Vali67b04462016-06-11 16:41:54 +00001109 auto C = CurLSI->getCXXThisCapture();
1110
1111 if (C.isCopyCapture()) {
1112 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1113 if (CurLSI->CallOperator->isConst())
1114 ClassType.addConst();
1115 return ASTCtx.getPointerType(ClassType);
1116 }
1117 }
Faisal Vali999f27e2017-05-02 20:56:34 +00001118
1119 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1120 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +00001121 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +00001122 assert(CurLSI && "While computing 'this' capture-type for a generic "
1123 "lambda, we must have a corresponding LambdaScopeInfo");
1124 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1125 "While computing 'this' capture-type for a generic lambda, when we "
1126 "run out of enclosing LSI's, yet the enclosing DC is a "
1127 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1128 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +00001129 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001130
Faisal Vali67b04462016-06-11 16:41:54 +00001131 auto IsThisCaptured =
1132 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1133 IsConst = false;
1134 IsByCopy = false;
1135 for (auto &&C : Closure->captures()) {
1136 if (C.capturesThis()) {
1137 if (C.getCaptureKind() == LCK_StarThis)
1138 IsByCopy = true;
1139 if (Closure->getLambdaCallOperator()->isConst())
1140 IsConst = true;
1141 return true;
1142 }
1143 }
1144 return false;
1145 };
1146
1147 bool IsByCopyCapture = false;
1148 bool IsConstCapture = false;
1149 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1150 while (Closure &&
1151 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1152 if (IsByCopyCapture) {
1153 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1154 if (IsConstCapture)
1155 ClassType.addConst();
1156 return ASTCtx.getPointerType(ClassType);
1157 }
1158 Closure = isLambdaCallOperator(Closure->getParent())
1159 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1160 : nullptr;
1161 }
1162 }
1163 return ASTCtx.getPointerType(ClassType);
1164}
1165
Eli Friedman73a04092012-01-07 04:59:52 +00001166QualType Sema::getCurrentThisType() {
1167 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001168 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001169
Richard Smith938f40b2011-06-11 17:19:42 +00001170 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1171 if (method && method->isInstance())
Brian Gesiak5488ab42019-01-11 01:54:53 +00001172 ThisTy = method->getThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001173 }
Faisal Validc6b5962016-03-21 09:25:37 +00001174
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001175 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001176 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001177
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001178 assert(isa<CXXRecordDecl>(DC) &&
1179 "Trying to get 'this' type from static method?");
1180
1181 // This is a lambda call operator that is being instantiated as a default
1182 // initializer. DC must point to the enclosing class type, so we can recover
1183 // the 'this' type from it.
1184
1185 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1186 // There are no cv-qualifiers for 'this' within default initializers,
1187 // per [expr.prim.general]p4.
1188 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001189 }
Faisal Vali67b04462016-06-11 16:41:54 +00001190
1191 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1192 // might need to be adjusted if the lambda or any of its enclosing lambda's
1193 // captures '*this' by copy.
1194 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1195 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1196 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001197 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001198}
1199
Simon Pilgrim75c26882016-09-30 14:25:09 +00001200Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001201 Decl *ContextDecl,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001202 Qualifiers CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001203 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001204 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1205{
1206 if (!Enabled || !ContextDecl)
1207 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001208
1209 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001210 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1211 Record = Template->getTemplatedDecl();
1212 else
1213 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001214
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001215 QualType T = S.Context.getRecordType(Record);
1216 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1217
1218 S.CXXThisTypeOverride = S.Context.getPointerType(T);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001219
Douglas Gregor3024f072012-04-16 07:05:22 +00001220 this->Enabled = true;
1221}
1222
1223
1224Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1225 if (Enabled) {
1226 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1227 }
1228}
1229
Simon Pilgrim75c26882016-09-30 14:25:09 +00001230bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001231 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1232 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001233 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001234 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001235 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001236
Faisal Validc6b5962016-03-21 09:25:37 +00001237 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001238
Reid Kleckner87a31802018-03-12 21:43:02 +00001239 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1240 ? *FunctionScopeIndexToStopAt
1241 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001242
Simon Pilgrim75c26882016-09-30 14:25:09 +00001243 // Check that we can capture the *enclosing object* (referred to by '*this')
1244 // by the capturing-entity/closure (lambda/block/etc) at
1245 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1246
1247 // Note: The *enclosing object* can only be captured by-value by a
1248 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001249 // [*this] { ... }.
1250 // Every other capture of the *enclosing object* results in its by-reference
1251 // capture.
1252
1253 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1254 // stack), we can capture the *enclosing object* only if:
1255 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1256 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001257 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001258 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001259 // -- or, there is some enclosing closure 'E' that has already captured the
1260 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001261 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001262 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001263 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001264
1265
Faisal Validc6b5962016-03-21 09:25:37 +00001266 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001267 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001268 if (CapturingScopeInfo *CSI =
1269 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1270 if (CSI->CXXThisCaptureIndex != 0) {
1271 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001272 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001273 break;
1274 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001275 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1276 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1277 // This context can't implicitly capture 'this'; fail out.
1278 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001279 Diag(Loc, diag::err_this_capture)
1280 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001281 return true;
1282 }
Eli Friedman20139d32012-01-11 02:36:31 +00001283 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001284 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001285 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001286 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001287 (Explicit && idx == MaxFunctionScopesIndex)) {
1288 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1289 // iteration through can be an explicit capture, all enclosing closures,
1290 // if any, must perform implicit captures.
1291
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001292 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001293 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001294 continue;
1295 }
Eli Friedman20139d32012-01-11 02:36:31 +00001296 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001297 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001298 Diag(Loc, diag::err_this_capture)
1299 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001300 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001301 }
Eli Friedman73a04092012-01-07 04:59:52 +00001302 break;
1303 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001304 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001305
1306 // If we got here, then the closure at MaxFunctionScopesIndex on the
1307 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1308 // (including implicit by-reference captures in any enclosing closures).
1309
1310 // In the loop below, respect the ByCopy flag only for the closure requesting
1311 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001312 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001313 // implicitly capturing the *enclosing object* by reference (see loop
1314 // above)).
1315 assert((!ByCopy ||
1316 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1317 "Only a lambda can capture the enclosing object (referred to by "
1318 "*this) by copy");
Faisal Vali67b04462016-06-11 16:41:54 +00001319 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001320 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1321 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001322 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001323
Richard Smith30116532019-05-28 23:09:46 +00001324 // The type of the corresponding data member (not a 'this' pointer if 'by
1325 // copy').
1326 QualType CaptureType = ThisTy;
1327 if (ByCopy) {
1328 // If we are capturing the object referred to by '*this' by copy, ignore
1329 // any cv qualifiers inherited from the type of the member function for
1330 // the type of the closure-type's corresponding data member and any use
1331 // of 'this'.
1332 CaptureType = ThisTy->getPointeeType();
1333 CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1334 }
1335
Faisal Validc6b5962016-03-21 09:25:37 +00001336 bool isNested = NumCapturingClosures > 1;
Richard Smithb5a45bb2019-05-31 01:17:04 +00001337 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001338 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001339 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001340}
1341
Richard Smith938f40b2011-06-11 17:19:42 +00001342ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001343 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1344 /// is a non-lvalue expression whose value is the address of the object for
1345 /// which the function is called.
1346
Douglas Gregor09deffa2011-10-18 16:47:30 +00001347 QualType ThisTy = getCurrentThisType();
Richard Smith8458c9e2019-05-24 01:35:07 +00001348 if (ThisTy.isNull())
1349 return Diag(Loc, diag::err_invalid_this_use);
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001350 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
Richard Smith8458c9e2019-05-24 01:35:07 +00001351}
John McCallf3a88602011-02-03 08:15:49 +00001352
Richard Smith8458c9e2019-05-24 01:35:07 +00001353Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1354 bool IsImplicit) {
1355 auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1356 MarkThisReferenced(This);
1357 return This;
1358}
1359
1360void Sema::MarkThisReferenced(CXXThisExpr *This) {
1361 CheckCXXThisCapture(This->getExprLoc());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001362}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001363
Douglas Gregor3024f072012-04-16 07:05:22 +00001364bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1365 // If we're outside the body of a member function, then we'll have a specified
1366 // type for 'this'.
1367 if (CXXThisTypeOverride.isNull())
1368 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001369
Douglas Gregor3024f072012-04-16 07:05:22 +00001370 // Determine whether we're looking into a class that's currently being
1371 // defined.
1372 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1373 return Class && Class->isBeingDefined();
1374}
1375
Vedant Kumara14a1f92018-01-17 18:53:51 +00001376/// Parse construction of a specified type.
1377/// Can be interpreted either as function-style casting ("int(x)")
1378/// or class type construction ("ClassType(x,y,z)")
1379/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001380ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001381Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001382 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001383 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001384 SourceLocation RParenOrBraceLoc,
1385 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001386 if (!TypeRep)
1387 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001388
John McCall97513962010-01-15 18:39:57 +00001389 TypeSourceInfo *TInfo;
1390 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1391 if (!TInfo)
1392 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001393
Vedant Kumara14a1f92018-01-17 18:53:51 +00001394 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1395 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001396 // Avoid creating a non-type-dependent expression that contains typos.
1397 // Non-type-dependent expressions are liable to be discarded without
1398 // checking for embedded typos.
1399 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1400 !Result.get()->isTypeDependent())
1401 Result = CorrectDelayedTyposInExpr(Result.get());
1402 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001403}
1404
Douglas Gregor2b88c112010-09-08 00:15:04 +00001405ExprResult
1406Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001407 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001408 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001409 SourceLocation RParenOrBraceLoc,
1410 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001411 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001412 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001413
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001414 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001415 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1416 // directly. We work around this by dropping the locations of the braces.
1417 SourceRange Locs = ListInitialization
1418 ? SourceRange()
1419 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1420 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1421 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001422 }
1423
Richard Smith600b5262017-01-26 20:40:47 +00001424 assert((!ListInitialization ||
1425 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1426 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001427 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001428
Richard Smith60437622017-02-09 19:17:44 +00001429 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1430 InitializationKind Kind =
1431 Exprs.size()
1432 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001433 ? InitializationKind::CreateDirectList(
1434 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1435 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1436 RParenOrBraceLoc)
1437 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1438 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001439
1440 // C++1z [expr.type.conv]p1:
1441 // If the type is a placeholder for a deduced class type, [...perform class
1442 // template argument deduction...]
1443 DeducedType *Deduced = Ty->getContainedDeducedType();
1444 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1445 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1446 Kind, Exprs);
1447 if (Ty.isNull())
1448 return ExprError();
1449 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1450 }
1451
Douglas Gregordd04d332009-01-16 18:33:17 +00001452 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001453 // If the expression list is a parenthesized single expression, the type
1454 // conversion expression is equivalent (in definedness, and if defined in
1455 // meaning) to the corresponding cast expression.
1456 if (Exprs.size() == 1 && !ListInitialization &&
1457 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001458 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001459 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1460 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001461 }
1462
Richard Smith49a6b6e2017-03-24 01:14:25 +00001463 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001464 QualType ElemTy = Ty;
1465 if (Ty->isArrayType()) {
1466 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001467 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1468 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001469 ElemTy = Context.getBaseElementType(Ty);
1470 }
1471
Richard Smith49a6b6e2017-03-24 01:14:25 +00001472 // There doesn't seem to be an explicit rule against this but sanity demands
1473 // we only construct objects with object types.
1474 if (Ty->isFunctionType())
1475 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1476 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001477
Richard Smith49a6b6e2017-03-24 01:14:25 +00001478 // C++17 [expr.type.conv]p2:
1479 // If the type is cv void and the initializer is (), the expression is a
1480 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001481 if (!Ty->isVoidType() &&
1482 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001483 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001484 return ExprError();
1485
Richard Smith49a6b6e2017-03-24 01:14:25 +00001486 // Otherwise, the expression is a prvalue of the specified type whose
1487 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001488 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1489 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001490
Richard Smith49a6b6e2017-03-24 01:14:25 +00001491 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001492 return Result;
1493
1494 Expr *Inner = Result.get();
1495 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1496 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001497 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1498 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001499 // If we created a CXXTemporaryObjectExpr, that node also represents the
1500 // functional cast. Otherwise, create an explicit cast to represent
1501 // the syntactic form of a functional-style cast that was used here.
1502 //
1503 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1504 // would give a more consistent AST representation than using a
1505 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1506 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001507 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001508 SourceRange Locs = ListInitialization
1509 ? SourceRange()
1510 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001511 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001512 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1513 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001514 }
1515
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001516 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001517}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001518
Artem Belevich78929ef2018-09-21 17:29:33 +00001519bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1520 // [CUDA] Ignore this function, if we can't call it.
1521 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1522 if (getLangOpts().CUDA &&
1523 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1524 return false;
1525
1526 SmallVector<const FunctionDecl*, 4> PreventedBy;
1527 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1528
1529 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1530 return Result;
1531
1532 // In case of CUDA, return true if none of the 1-argument deallocator
1533 // functions are actually callable.
1534 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1535 assert(FD->getNumParams() == 1 &&
1536 "Only single-operand functions should be in PreventedBy");
1537 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1538 });
1539}
1540
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001541/// Determine whether the given function is a non-placement
Richard Smithb2f0f052016-10-10 18:54:32 +00001542/// deallocation function.
1543static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001544 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
Artem Belevich78929ef2018-09-21 17:29:33 +00001545 return S.isUsualDeallocationFunction(Method);
Richard Smithb2f0f052016-10-10 18:54:32 +00001546
1547 if (FD->getOverloadedOperator() != OO_Delete &&
1548 FD->getOverloadedOperator() != OO_Array_Delete)
1549 return false;
1550
1551 unsigned UsualParams = 1;
1552
1553 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1554 S.Context.hasSameUnqualifiedType(
1555 FD->getParamDecl(UsualParams)->getType(),
1556 S.Context.getSizeType()))
1557 ++UsualParams;
1558
1559 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1560 S.Context.hasSameUnqualifiedType(
1561 FD->getParamDecl(UsualParams)->getType(),
1562 S.Context.getTypeDeclType(S.getStdAlignValT())))
1563 ++UsualParams;
1564
1565 return UsualParams == FD->getNumParams();
1566}
1567
1568namespace {
1569 struct UsualDeallocFnInfo {
1570 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001571 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001572 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001573 Destroying(false), HasSizeT(false), HasAlignValT(false),
1574 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001575 // A function template declaration is never a usual deallocation function.
1576 if (!FD)
1577 return;
Richard Smith5b349582017-10-13 01:55:36 +00001578 unsigned NumBaseParams = 1;
1579 if (FD->isDestroyingOperatorDelete()) {
1580 Destroying = true;
1581 ++NumBaseParams;
1582 }
Eric Fiselier8e920502019-01-16 02:34:36 +00001583
1584 if (NumBaseParams < FD->getNumParams() &&
1585 S.Context.hasSameUnqualifiedType(
1586 FD->getParamDecl(NumBaseParams)->getType(),
1587 S.Context.getSizeType())) {
1588 ++NumBaseParams;
1589 HasSizeT = true;
1590 }
1591
1592 if (NumBaseParams < FD->getNumParams() &&
1593 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1594 ++NumBaseParams;
1595 HasAlignValT = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001596 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001597
1598 // In CUDA, determine how much we'd like / dislike to call this.
1599 if (S.getLangOpts().CUDA)
1600 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1601 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001602 }
1603
Eric Fiselierfa752f22018-03-21 19:19:48 +00001604 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001605
Richard Smithf75dcbe2016-10-11 00:21:10 +00001606 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1607 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001608 // C++ P0722:
1609 // A destroying operator delete is preferred over a non-destroying
1610 // operator delete.
1611 if (Destroying != Other.Destroying)
1612 return Destroying;
1613
Richard Smithf75dcbe2016-10-11 00:21:10 +00001614 // C++17 [expr.delete]p10:
1615 // If the type has new-extended alignment, a function with a parameter
1616 // of type std::align_val_t is preferred; otherwise a function without
1617 // such a parameter is preferred
1618 if (HasAlignValT != Other.HasAlignValT)
1619 return HasAlignValT == WantAlign;
1620
1621 if (HasSizeT != Other.HasSizeT)
1622 return HasSizeT == WantSize;
1623
1624 // Use CUDA call preference as a tiebreaker.
1625 return CUDAPref > Other.CUDAPref;
1626 }
1627
Richard Smithb2f0f052016-10-10 18:54:32 +00001628 DeclAccessPair Found;
1629 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001630 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001631 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001632 };
1633}
1634
1635/// Determine whether a type has new-extended alignment. This may be called when
1636/// the type is incomplete (for a delete-expression with an incomplete pointee
1637/// type), in which case it will conservatively return false if the alignment is
1638/// not known.
1639static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1640 return S.getLangOpts().AlignedAllocation &&
1641 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1642 S.getASTContext().getTargetInfo().getNewAlign();
1643}
1644
1645/// Select the correct "usual" deallocation function to use from a selection of
1646/// deallocation functions (either global or class-scope).
1647static UsualDeallocFnInfo resolveDeallocationOverload(
1648 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1649 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1650 UsualDeallocFnInfo Best;
1651
Richard Smithb2f0f052016-10-10 18:54:32 +00001652 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001653 UsualDeallocFnInfo Info(S, I.getPair());
1654 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1655 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001656 continue;
1657
1658 if (!Best) {
1659 Best = Info;
1660 if (BestFns)
1661 BestFns->push_back(Info);
1662 continue;
1663 }
1664
Richard Smithf75dcbe2016-10-11 00:21:10 +00001665 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001666 continue;
1667
1668 // If more than one preferred function is found, all non-preferred
1669 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001670 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001671 BestFns->clear();
1672
1673 Best = Info;
1674 if (BestFns)
1675 BestFns->push_back(Info);
1676 }
1677
1678 return Best;
1679}
1680
1681/// Determine whether a given type is a class for which 'delete[]' would call
1682/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1683/// we need to store the array size (even if the type is
1684/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001685static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1686 QualType allocType) {
1687 const RecordType *record =
1688 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1689 if (!record) return false;
1690
1691 // Try to find an operator delete[] in class scope.
1692
1693 DeclarationName deleteName =
1694 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1695 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1696 S.LookupQualifiedName(ops, record->getDecl());
1697
1698 // We're just doing this for information.
1699 ops.suppressDiagnostics();
1700
1701 // Very likely: there's no operator delete[].
1702 if (ops.empty()) return false;
1703
1704 // If it's ambiguous, it should be illegal to call operator delete[]
1705 // on this thing, so it doesn't matter if we allocate extra space or not.
1706 if (ops.isAmbiguous()) return false;
1707
Richard Smithb2f0f052016-10-10 18:54:32 +00001708 // C++17 [expr.delete]p10:
1709 // If the deallocation functions have class scope, the one without a
1710 // parameter of type std::size_t is selected.
1711 auto Best = resolveDeallocationOverload(
1712 S, ops, /*WantSize*/false,
1713 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1714 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001715}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001716
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001717/// Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001718///
Sebastian Redld74dd492012-02-12 18:41:05 +00001719/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001720/// @code new (memory) int[size][4] @endcode
1721/// or
1722/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001723///
1724/// \param StartLoc The first location of the expression.
1725/// \param UseGlobal True if 'new' was prefixed with '::'.
1726/// \param PlacementLParen Opening paren of the placement arguments.
1727/// \param PlacementArgs Placement new arguments.
1728/// \param PlacementRParen Closing paren of the placement arguments.
1729/// \param TypeIdParens If the type is in parens, the source range.
1730/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001731/// \param Initializer The initializing expression or initializer-list, or null
1732/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001733ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001734Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001735 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001736 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001737 Declarator &D, Expr *Initializer) {
Richard Smithb9fb1212019-05-06 03:47:15 +00001738 Optional<Expr *> ArraySize;
Sebastian Redl351bb782008-12-02 14:43:59 +00001739 // If the specified type is an array, unwrap it and save the expression.
1740 if (D.getNumTypeObjects() > 0 &&
1741 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001742 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001743 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001744 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1745 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001746 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001747 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1748 << D.getSourceRange());
Richard Smithb9fb1212019-05-06 03:47:15 +00001749 if (!Chunk.Arr.NumElts && !Initializer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001750 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1751 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001752
Sebastian Redl351bb782008-12-02 14:43:59 +00001753 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001754 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001755 }
1756
Douglas Gregor73341c42009-09-11 00:18:58 +00001757 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001758 if (ArraySize) {
1759 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001760 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1761 break;
1762
1763 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1764 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001765 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001766 if (getLangOpts().CPlusPlus14) {
Fangrui Song99337e22018-07-20 08:19:20 +00001767 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1768 // shall be a converted constant expression (5.19) of type std::size_t
1769 // and shall evaluate to a strictly positive value.
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001770 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1771 assert(IntWidth && "Builtin type of size 0?");
1772 llvm::APSInt Value(IntWidth);
1773 Array.NumElts
1774 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1775 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001776 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001777 } else {
1778 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001779 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001780 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001781 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001782 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001783 if (!Array.NumElts)
1784 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001785 }
1786 }
1787 }
1788 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001789
Craig Topperc3ec1492014-05-26 06:22:03 +00001790 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001791 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001792 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001793 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001794
Sebastian Redl6047f072012-02-16 12:22:20 +00001795 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001796 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001797 DirectInitRange = List->getSourceRange();
1798
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001799 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1800 PlacementLParen, PlacementArgs, PlacementRParen,
1801 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001802 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001803}
1804
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001805static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1806 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001807 if (!Init)
1808 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001809 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1810 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001811 if (isa<ImplicitValueInitExpr>(Init))
1812 return true;
1813 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1814 return !CCE->isListInitialization() &&
1815 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001816 else if (Style == CXXNewExpr::ListInit) {
1817 assert(isa<InitListExpr>(Init) &&
1818 "Shouldn't create list CXXConstructExprs for arrays.");
1819 return true;
1820 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001821 return false;
1822}
1823
Akira Hatanaka71645c22018-12-21 07:05:36 +00001824bool
1825Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1826 if (!getLangOpts().AlignedAllocationUnavailable)
1827 return false;
1828 if (FD.isDefined())
1829 return false;
Roman Lebedev3dd5a292020-02-26 01:37:17 +03001830 Optional<unsigned> AlignmentParam;
1831 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
1832 AlignmentParam.hasValue())
Akira Hatanaka71645c22018-12-21 07:05:36 +00001833 return true;
1834 return false;
1835}
1836
Akira Hatanakacae83f72017-06-29 18:48:40 +00001837// Emit a diagnostic if an aligned allocation/deallocation function that is not
1838// implemented in the standard library is selected.
Akira Hatanaka71645c22018-12-21 07:05:36 +00001839void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1840 SourceLocation Loc) {
1841 if (isUnavailableAlignedAllocationFunction(FD)) {
1842 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001843 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
Akira Hatanaka71645c22018-12-21 07:05:36 +00001844 getASTContext().getTargetInfo().getPlatformName());
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001845
Akira Hatanaka71645c22018-12-21 07:05:36 +00001846 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1847 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1848 Diag(Loc, diag::err_aligned_allocation_unavailable)
Volodymyr Sapsaie5015ab2018-08-03 23:12:37 +00001849 << IsDelete << FD.getType().getAsString() << OSName
1850 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanaka71645c22018-12-21 07:05:36 +00001851 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
Akira Hatanakacae83f72017-06-29 18:48:40 +00001852 }
1853}
1854
John McCalldadc5752010-08-24 06:29:42 +00001855ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001856Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001857 SourceLocation PlacementLParen,
1858 MultiExprArg PlacementArgs,
1859 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001860 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001861 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001862 TypeSourceInfo *AllocTypeInfo,
Richard Smithb9fb1212019-05-06 03:47:15 +00001863 Optional<Expr *> ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001864 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001865 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001866 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001867 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001868
Sebastian Redl6047f072012-02-16 12:22:20 +00001869 CXXNewExpr::InitializationStyle initStyle;
1870 if (DirectInitRange.isValid()) {
1871 assert(Initializer && "Have parens but no initializer.");
1872 initStyle = CXXNewExpr::CallInit;
1873 } else if (Initializer && isa<InitListExpr>(Initializer))
1874 initStyle = CXXNewExpr::ListInit;
1875 else {
1876 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1877 isa<CXXConstructExpr>(Initializer)) &&
1878 "Initializer expression that cannot have been implicitly created.");
1879 initStyle = CXXNewExpr::NoInit;
1880 }
1881
1882 Expr **Inits = &Initializer;
1883 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001884 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1885 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1886 Inits = List->getExprs();
1887 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001888 }
1889
Richard Smith60437622017-02-09 19:17:44 +00001890 // C++11 [expr.new]p15:
1891 // A new-expression that creates an object of type T initializes that
1892 // object as follows:
1893 InitializationKind Kind
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001894 // - If the new-initializer is omitted, the object is default-
1895 // initialized (8.5); if no initialization is performed,
1896 // the object has indeterminate value
1897 = initStyle == CXXNewExpr::NoInit
1898 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1899 // - Otherwise, the new-initializer is interpreted according to
1900 // the
1901 // initialization rules of 8.5 for direct-initialization.
1902 : initStyle == CXXNewExpr::ListInit
1903 ? InitializationKind::CreateDirectList(
1904 TypeRange.getBegin(), Initializer->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001905 Initializer->getEndLoc())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001906 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1907 DirectInitRange.getBegin(),
1908 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001909
Richard Smith60437622017-02-09 19:17:44 +00001910 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1911 auto *Deduced = AllocType->getContainedDeducedType();
1912 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1913 if (ArraySize)
Richard Smithb9fb1212019-05-06 03:47:15 +00001914 return ExprError(
1915 Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
1916 diag::err_deduced_class_template_compound_type)
1917 << /*array*/ 2
1918 << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
Richard Smith60437622017-02-09 19:17:44 +00001919
1920 InitializedEntity Entity
1921 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1922 AllocType = DeduceTemplateSpecializationFromInitializer(
1923 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1924 if (AllocType.isNull())
1925 return ExprError();
1926 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001927 bool Braced = (initStyle == CXXNewExpr::ListInit);
1928 if (NumInits == 1) {
1929 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1930 Inits = p->getInits();
1931 NumInits = p->getNumInits();
1932 Braced = true;
1933 }
1934 }
1935
Sebastian Redl6047f072012-02-16 12:22:20 +00001936 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001937 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1938 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001939 if (NumInits > 1) {
1940 Expr *FirstBad = Inits[1];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001941 return ExprError(Diag(FirstBad->getBeginLoc(),
Richard Smith30482bc2011-02-20 03:19:35 +00001942 diag::err_auto_new_ctor_multiple_expressions)
1943 << AllocType << TypeRange);
1944 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001945 if (Braced && !getLangOpts().CPlusPlus17)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001946 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001947 << AllocType << TypeRange;
Richard Smith42a22372019-04-24 02:22:38 +00001948 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001949 QualType DeducedType;
Richard Smith42a22372019-04-24 02:22:38 +00001950 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001951 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Richard Smith42a22372019-04-24 02:22:38 +00001952 << AllocType << Deduce->getType()
1953 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001954 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001955 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001956 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001957 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001958
Douglas Gregorcda95f42010-05-16 16:01:03 +00001959 // Per C++0x [expr.new]p5, the type being constructed may be a
1960 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001961 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001962 if (const ConstantArrayType *Array
1963 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001964 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1965 Context.getSizeType(),
1966 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001967 AllocType = Array->getElementType();
1968 }
1969 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001970
Douglas Gregor3999e152010-10-06 16:00:31 +00001971 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1972 return ExprError();
1973
Simon Pilgrim75c26882016-09-30 14:25:09 +00001974 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001975 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001976 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1977 AllocType->isObjCLifetimeType()) {
1978 AllocType = Context.getLifetimeQualifiedType(AllocType,
1979 AllocType->getObjCARCImplicitLifetime());
1980 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001981
John McCall31168b02011-06-15 23:02:42 +00001982 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001983
Richard Smithb9fb1212019-05-06 03:47:15 +00001984 if (ArraySize && *ArraySize &&
1985 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
1986 ExprResult result = CheckPlaceholderExpr(*ArraySize);
John McCall5e77d762013-04-16 07:28:30 +00001987 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001988 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001989 }
Richard Smith8dd34252012-02-04 07:07:42 +00001990 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1991 // integral or enumeration type with a non-negative value."
1992 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1993 // enumeration type, or a class type for which a single non-explicit
1994 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001995 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001996 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001997 llvm::Optional<uint64_t> KnownArraySize;
Richard Smithb9fb1212019-05-06 03:47:15 +00001998 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001999 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002000 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00002001 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2002
Richard Smithb9fb1212019-05-06 03:47:15 +00002003 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
Fangrui Song99337e22018-07-20 08:19:20 +00002004 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00002005
Simon Pilgrim75c26882016-09-30 14:25:09 +00002006 if (!ConvertedSize.isInvalid() &&
Richard Smithb9fb1212019-05-06 03:47:15 +00002007 (*ArraySize)->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00002008 // Diagnose the compatibility of this conversion.
2009 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
Richard Smithb9fb1212019-05-06 03:47:15 +00002010 << (*ArraySize)->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002011 } else {
2012 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2013 protected:
2014 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00002015
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002016 public:
2017 SizeConvertDiagnoser(Expr *ArraySize)
2018 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2019 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002020
2021 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2022 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002023 return S.Diag(Loc, diag::err_array_size_not_integral)
2024 << S.getLangOpts().CPlusPlus11 << T;
2025 }
Craig Toppere14c0f82014-03-12 04:55:44 +00002026
2027 SemaDiagnosticBuilder diagnoseIncomplete(
2028 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002029 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2030 << T << ArraySize->getSourceRange();
2031 }
Craig Toppere14c0f82014-03-12 04:55:44 +00002032
2033 SemaDiagnosticBuilder diagnoseExplicitConv(
2034 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002035 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2036 }
Craig Toppere14c0f82014-03-12 04:55:44 +00002037
2038 SemaDiagnosticBuilder noteExplicitConv(
2039 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002040 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2041 << ConvTy->isEnumeralType() << ConvTy;
2042 }
Craig Toppere14c0f82014-03-12 04:55:44 +00002043
2044 SemaDiagnosticBuilder diagnoseAmbiguous(
2045 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002046 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2047 }
Craig Toppere14c0f82014-03-12 04:55:44 +00002048
2049 SemaDiagnosticBuilder noteAmbiguous(
2050 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002051 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2052 << ConvTy->isEnumeralType() << ConvTy;
2053 }
Richard Smithccc11812013-05-21 19:05:48 +00002054
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002055 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2056 QualType T,
2057 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002058 return S.Diag(Loc,
2059 S.getLangOpts().CPlusPlus11
2060 ? diag::warn_cxx98_compat_array_size_conversion
2061 : diag::ext_array_size_conversion)
2062 << T << ConvTy->isEnumeralType() << ConvTy;
2063 }
Richard Smithb9fb1212019-05-06 03:47:15 +00002064 } SizeDiagnoser(*ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00002065
Richard Smithb9fb1212019-05-06 03:47:15 +00002066 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002067 SizeDiagnoser);
2068 }
Douglas Gregor4799d032010-06-30 00:20:43 +00002069 if (ConvertedSize.isInvalid())
2070 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002071
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002072 ArraySize = ConvertedSize.get();
Richard Smithb9fb1212019-05-06 03:47:15 +00002073 QualType SizeType = (*ArraySize)->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002074
Douglas Gregor0bf31402010-10-08 23:50:27 +00002075 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00002076 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002077
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002078 // C++98 [expr.new]p7:
2079 // The expression in a direct-new-declarator shall have integral type
2080 // with a non-negative value.
2081 //
Richard Smith0511d232016-10-05 22:41:02 +00002082 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2083 // per CWG1464. Otherwise, if it's not a constant, we must have an
2084 // unparenthesized array type.
Richard Smithb9fb1212019-05-06 03:47:15 +00002085 if (!(*ArraySize)->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002086 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00002087 // We've already performed any required implicit conversion to integer or
2088 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00002089 // FIXME: Per CWG1464, we are required to check the value prior to
2090 // converting to size_t. This will never find a negative array size in
2091 // C++14 onwards, because Value is always unsigned here!
Richard Smithb9fb1212019-05-06 03:47:15 +00002092 if ((*ArraySize)->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00002093 if (Value.isSigned() && Value.isNegative()) {
Richard Smithb9fb1212019-05-06 03:47:15 +00002094 return ExprError(Diag((*ArraySize)->getBeginLoc(),
Richard Smith0511d232016-10-05 22:41:02 +00002095 diag::err_typecheck_negative_array_size)
Richard Smithb9fb1212019-05-06 03:47:15 +00002096 << (*ArraySize)->getSourceRange());
Richard Smith0511d232016-10-05 22:41:02 +00002097 }
2098
2099 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002100 unsigned ActiveSizeBits =
2101 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00002102 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002103 return ExprError(
Richard Smithb9fb1212019-05-06 03:47:15 +00002104 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2105 << Value.toString(10) << (*ArraySize)->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002106 }
Richard Smith0511d232016-10-05 22:41:02 +00002107
2108 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00002109 } else if (TypeIdParens.isValid()) {
2110 // Can't have dynamic array size when the type-id is in parentheses.
Richard Smithb9fb1212019-05-06 03:47:15 +00002111 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2112 << (*ArraySize)->getSourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002113 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2114 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002115
Douglas Gregorf2753b32010-07-13 15:54:32 +00002116 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002117 }
Sebastian Redl351bb782008-12-02 14:43:59 +00002118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002119
John McCall036f2f62011-05-15 07:14:44 +00002120 // Note that we do *not* convert the argument in any way. It can
2121 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00002122 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002123
Craig Topperc3ec1492014-05-26 06:22:03 +00002124 FunctionDecl *OperatorNew = nullptr;
2125 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00002126 unsigned Alignment =
2127 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2128 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2129 bool PassAlignment = getLangOpts().AlignedAllocation &&
2130 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002131
Brian Gesiakcb024022018-04-01 22:59:22 +00002132 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002133 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002134 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Richard Smithb9fb1212019-05-06 03:47:15 +00002135 FindAllocationFunctions(
2136 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2137 AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
2138 OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002139 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00002140
2141 // If this is an array allocation, compute whether the usual array
2142 // deallocation function for the type has a size_t parameter.
2143 bool UsualArrayDeleteWantsSize = false;
2144 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00002145 UsualArrayDeleteWantsSize =
2146 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00002147
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002148 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00002149 if (OperatorNew) {
Simon Pilgrim94885432020-03-04 11:25:34 +00002150 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
Richard Smithd6f9e732014-05-13 19:56:21 +00002151 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2152 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002153
Richard Smithd6f9e732014-05-13 19:56:21 +00002154 // We've already converted the placement args, just fill in any default
2155 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002156 // argument. Skip the second parameter too if we're passing in the
2157 // alignment; we've already filled it in.
Roman Lebedevb8fdafe2020-02-26 01:36:44 +03002158 unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
Richard Smithb2f0f052016-10-10 18:54:32 +00002159 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
Roman Lebedevb8fdafe2020-02-26 01:36:44 +03002160 NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2161 CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002162 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002164 if (!AllPlaceArgs.empty())
2165 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002166
Roman Lebedevb8fdafe2020-02-26 01:36:44 +03002167 // We would like to perform some checking on the given `operator new` call,
2168 // but the PlacementArgs does not contain the implicit arguments,
2169 // namely allocation size and maybe allocation alignment,
2170 // so we need to conjure them.
Eli Friedmanff4b4072012-02-18 04:48:30 +00002171
Roman Lebedevb8fdafe2020-02-26 01:36:44 +03002172 QualType SizeTy = Context.getSizeType();
2173 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2174
2175 llvm::APInt SingleEltSize(
2176 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2177
2178 // How many bytes do we want to allocate here?
2179 llvm::Optional<llvm::APInt> AllocationSize;
2180 if (!ArraySize.hasValue() && !AllocType->isDependentType()) {
2181 // For non-array operator new, we only want to allocate one element.
2182 AllocationSize = SingleEltSize;
2183 } else if (KnownArraySize.hasValue() && !AllocType->isDependentType()) {
2184 // For array operator new, only deal with static array size case.
2185 bool Overflow;
2186 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2187 .umul_ov(SingleEltSize, Overflow);
2188 (void)Overflow;
2189 assert(
2190 !Overflow &&
2191 "Expected that all the overflows would have been handled already.");
2192 }
2193
2194 IntegerLiteral AllocationSizeLiteral(
2195 Context,
2196 AllocationSize.getValueOr(llvm::APInt::getNullValue(SizeTyWidth)),
2197 SizeTy, SourceLocation());
2198 // Otherwise, if we failed to constant-fold the allocation size, we'll
2199 // just give up and pass-in something opaque, that isn't a null pointer.
2200 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_RValue,
2201 OK_Ordinary, /*SourceExpr=*/nullptr);
2202
2203 // Let's synthesize the alignment argument in case we will need it.
2204 // Since we *really* want to allocate these on stack, this is slightly ugly
2205 // because there might not be a `std::align_val_t` type.
2206 EnumDecl *StdAlignValT = getStdAlignValT();
2207 QualType AlignValT =
2208 StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy;
2209 IntegerLiteral AlignmentLiteral(
2210 Context,
2211 llvm::APInt(Context.getTypeSize(SizeTy),
2212 Alignment / Context.getCharWidth()),
2213 SizeTy, SourceLocation());
2214 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2215 CK_IntegralCast, &AlignmentLiteral,
2216 VK_RValue);
2217
2218 // Adjust placement args by prepending conjured size and alignment exprs.
2219 llvm::SmallVector<Expr *, 8> CallArgs;
2220 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2221 CallArgs.emplace_back(AllocationSize.hasValue()
2222 ? static_cast<Expr *>(&AllocationSizeLiteral)
2223 : &OpaqueAllocationSize);
2224 if (PassAlignment)
2225 CallArgs.emplace_back(&DesiredAlignment);
2226 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2227
2228 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2229
2230 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2231 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002232
Richard Smithb2f0f052016-10-10 18:54:32 +00002233 // Warn if the type is over-aligned and is being allocated by (unaligned)
2234 // global operator new.
2235 if (PlacementArgs.empty() && !PassAlignment &&
2236 (OperatorNew->isImplicit() ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002237 (OperatorNew->getBeginLoc().isValid() &&
2238 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002239 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002240 Diag(StartLoc, diag::warn_overaligned_type)
2241 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002242 << unsigned(Alignment / Context.getCharWidth())
2243 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002244 }
2245 }
2246
Sebastian Redl6047f072012-02-16 12:22:20 +00002247 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002248 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2249 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002250 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002251 SourceRange InitRange(Inits[0]->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002252 Inits[NumInits - 1]->getEndLoc());
Richard Smith0511d232016-10-05 22:41:02 +00002253 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2254 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002255 }
2256
Richard Smithdd2ca572012-11-26 08:32:48 +00002257 // If we can perform the initialization, and we've not already done so,
2258 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002259 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002260 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002261 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002262 // The type we initialize is the complete type, including the array bound.
2263 QualType InitType;
2264 if (KnownArraySize)
2265 InitType = Context.getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00002266 AllocType,
2267 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2268 *KnownArraySize),
2269 *ArraySize, ArrayType::Normal, 0);
Richard Smith0511d232016-10-05 22:41:02 +00002270 else if (ArraySize)
2271 InitType =
2272 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2273 else
2274 InitType = AllocType;
2275
Douglas Gregor85dabae2009-12-16 01:38:02 +00002276 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002277 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002278 InitializationSequence InitSeq(*this, Entity, Kind,
2279 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002280 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002281 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002282 if (FullInit.isInvalid())
2283 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002284
Sebastian Redl6047f072012-02-16 12:22:20 +00002285 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2286 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002287 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002288 if (CXXBindTemporaryExpr *Binder =
2289 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002290 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002291
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002292 Initializer = FullInit.get();
Richard Smithb9fb1212019-05-06 03:47:15 +00002293
2294 // FIXME: If we have a KnownArraySize, check that the array bound of the
2295 // initializer is no greater than that constant value.
2296
2297 if (ArraySize && !*ArraySize) {
2298 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2299 if (CAT) {
2300 // FIXME: Track that the array size was inferred rather than explicitly
2301 // specified.
2302 ArraySize = IntegerLiteral::Create(
2303 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2304 } else {
2305 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2306 << Initializer->getSourceRange();
2307 }
2308 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002310
Douglas Gregor6642ca22010-02-26 05:06:18 +00002311 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002312 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002313 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2314 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002315 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00002316 }
2317 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002318 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2319 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002320 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00002321 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002322
Bruno Ricci9b6dfac2019-01-07 15:04:45 +00002323 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2324 PassAlignment, UsualArrayDeleteWantsSize,
2325 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2326 Initializer, ResultType, AllocTypeInfo, Range,
2327 DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002328}
2329
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002330/// Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002331/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002332bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002333 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002334 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2335 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002336 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002337 return Diag(Loc, diag::err_bad_new_type)
2338 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002339 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002340 return Diag(Loc, diag::err_bad_new_type)
2341 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002342 else if (!AllocType->isDependentType() &&
Richard Sandiford506406c2020-03-03 11:14:57 +00002343 RequireCompleteSizedType(
2344 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002345 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002346 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002347 diag::err_allocation_of_abstract_type))
2348 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002349 else if (AllocType->isVariablyModifiedType())
2350 return Diag(Loc, diag::err_variably_modified_new_type)
2351 << AllocType;
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002352 else if (AllocType.getAddressSpace() != LangAS::Default &&
2353 !getLangOpts().OpenCLCPlusPlus)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002354 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002355 << AllocType.getUnqualifiedType()
2356 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002357 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002358 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2359 QualType BaseAllocType = Context.getBaseElementType(AT);
2360 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2361 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002362 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002363 << BaseAllocType;
2364 }
2365 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002366
Sebastian Redlbd150f42008-11-21 19:14:01 +00002367 return false;
2368}
2369
Brian Gesiak87412d92018-02-15 20:09:25 +00002370static bool resolveAllocationOverload(
2371 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2372 bool &PassAlignment, FunctionDecl *&Operator,
2373 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002374 OverloadCandidateSet Candidates(R.getNameLoc(),
2375 OverloadCandidateSet::CSK_Normal);
2376 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2377 Alloc != AllocEnd; ++Alloc) {
2378 // Even member operator new/delete are implicitly treated as
2379 // static, so don't use AddMemberCandidate.
2380 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2381
2382 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2383 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2384 /*ExplicitTemplateArgs=*/nullptr, Args,
2385 Candidates,
2386 /*SuppressUserConversions=*/false);
2387 continue;
2388 }
2389
2390 FunctionDecl *Fn = cast<FunctionDecl>(D);
2391 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2392 /*SuppressUserConversions=*/false);
2393 }
2394
2395 // Do the resolution.
2396 OverloadCandidateSet::iterator Best;
2397 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2398 case OR_Success: {
2399 // Got one!
2400 FunctionDecl *FnDecl = Best->Function;
2401 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2402 Best->FoundDecl) == Sema::AR_inaccessible)
2403 return true;
2404
2405 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002406 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002407 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002408
Richard Smithb2f0f052016-10-10 18:54:32 +00002409 case OR_No_Viable_Function:
2410 // C++17 [expr.new]p13:
2411 // If no matching function is found and the allocated object type has
2412 // new-extended alignment, the alignment argument is removed from the
2413 // argument list, and overload resolution is performed again.
2414 if (PassAlignment) {
2415 PassAlignment = false;
2416 AlignArg = Args[1];
2417 Args.erase(Args.begin() + 1);
2418 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002419 Operator, &Candidates, AlignArg,
2420 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002421 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002422
Richard Smithb2f0f052016-10-10 18:54:32 +00002423 // MSVC will fall back on trying to find a matching global operator new
2424 // if operator new[] cannot be found. Also, MSVC will leak by not
2425 // generating a call to operator delete or operator delete[], but we
2426 // will not replicate that bug.
2427 // FIXME: Find out how this interacts with the std::align_val_t fallback
2428 // once MSVC implements it.
2429 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2430 S.Context.getLangOpts().MSVCCompat) {
2431 R.clear();
2432 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2433 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2434 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2435 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002436 Operator, /*Candidates=*/nullptr,
2437 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002438 }
Richard Smith1cdec012013-09-29 04:40:38 +00002439
Brian Gesiak87412d92018-02-15 20:09:25 +00002440 if (Diagnose) {
David Blaikie5e328052019-05-03 00:44:50 +00002441 PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call)
2442 << R.getLookupName() << Range);
Richard Smithb2f0f052016-10-10 18:54:32 +00002443
Brian Gesiak87412d92018-02-15 20:09:25 +00002444 // If we have aligned candidates, only note the align_val_t candidates
2445 // from AlignedCandidates and the non-align_val_t candidates from
2446 // Candidates.
2447 if (AlignedCandidates) {
2448 auto IsAligned = [](OverloadCandidate &C) {
2449 return C.Function->getNumParams() > 1 &&
2450 C.Function->getParamDecl(1)->getType()->isAlignValT();
2451 };
2452 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002453
Brian Gesiak87412d92018-02-15 20:09:25 +00002454 // This was an overaligned allocation, so list the aligned candidates
2455 // first.
2456 Args.insert(Args.begin() + 1, AlignArg);
David Blaikie5e328052019-05-03 00:44:50 +00002457 AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "",
Brian Gesiak87412d92018-02-15 20:09:25 +00002458 R.getNameLoc(), IsAligned);
2459 Args.erase(Args.begin() + 1);
David Blaikie5e328052019-05-03 00:44:50 +00002460 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(),
Brian Gesiak87412d92018-02-15 20:09:25 +00002461 IsUnaligned);
2462 } else {
David Blaikie5e328052019-05-03 00:44:50 +00002463 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args);
Brian Gesiak87412d92018-02-15 20:09:25 +00002464 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002465 }
Richard Smith1cdec012013-09-29 04:40:38 +00002466 return true;
2467
Richard Smithb2f0f052016-10-10 18:54:32 +00002468 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002469 if (Diagnose) {
David Blaikie5e328052019-05-03 00:44:50 +00002470 Candidates.NoteCandidates(
2471 PartialDiagnosticAt(R.getNameLoc(),
2472 S.PDiag(diag::err_ovl_ambiguous_call)
2473 << R.getLookupName() << Range),
Richard Smith70f59b52019-10-23 17:54:10 -07002474 S, OCD_AmbiguousCandidates, Args);
Brian Gesiak87412d92018-02-15 20:09:25 +00002475 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002476 return true;
2477
2478 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002479 if (Diagnose) {
David Blaikie5e328052019-05-03 00:44:50 +00002480 Candidates.NoteCandidates(
2481 PartialDiagnosticAt(R.getNameLoc(),
2482 S.PDiag(diag::err_ovl_deleted_call)
2483 << R.getLookupName() << Range),
2484 S, OCD_AllCandidates, Args);
Brian Gesiak87412d92018-02-15 20:09:25 +00002485 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002486 return true;
2487 }
2488 }
2489 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002490}
2491
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002492bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002493 AllocationFunctionScope NewScope,
2494 AllocationFunctionScope DeleteScope,
2495 QualType AllocType, bool IsArray,
2496 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002497 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002498 FunctionDecl *&OperatorDelete,
2499 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002500 // --- Choosing an allocation function ---
2501 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002502 // 1) If looking in AFS_Global scope for allocation functions, only look in
2503 // the global scope. Else, if AFS_Class, only look in the scope of the
2504 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002505 // 2) If an array size is given, look for operator new[], else look for
2506 // operator new.
2507 // 3) The first argument is always size_t. Append the arguments from the
2508 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002509
Richard Smithb2f0f052016-10-10 18:54:32 +00002510 SmallVector<Expr*, 8> AllocArgs;
2511 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2512
2513 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002514 // FIXME: Should the Sema create the expression and embed it in the syntax
2515 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002516 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002517 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002518 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002519 Context.getSizeType(),
2520 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002521 AllocArgs.push_back(&Size);
2522
2523 QualType AlignValT = Context.VoidTy;
2524 if (PassAlignment) {
2525 DeclareGlobalNewDelete();
2526 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2527 }
2528 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2529 if (PassAlignment)
2530 AllocArgs.push_back(&Align);
2531
2532 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002533
Douglas Gregor6642ca22010-02-26 05:06:18 +00002534 // C++ [expr.new]p8:
2535 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002536 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002537 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002538 // type, the allocation function's name is operator new[] and the
2539 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002540 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002541 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002542
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002543 QualType AllocElemType = Context.getBaseElementType(AllocType);
2544
Richard Smithb2f0f052016-10-10 18:54:32 +00002545 // Find the allocation function.
2546 {
2547 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2548
2549 // C++1z [expr.new]p9:
2550 // If the new-expression begins with a unary :: operator, the allocation
2551 // function's name is looked up in the global scope. Otherwise, if the
2552 // allocated type is a class type T or array thereof, the allocation
2553 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002554 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002555 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2556
2557 // We can see ambiguity here if the allocation function is found in
2558 // multiple base classes.
2559 if (R.isAmbiguous())
2560 return true;
2561
2562 // If this lookup fails to find the name, or if the allocated type is not
2563 // a class type, the allocation function's name is looked up in the
2564 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002565 if (R.empty()) {
2566 if (NewScope == AFS_Class)
2567 return true;
2568
Richard Smithb2f0f052016-10-10 18:54:32 +00002569 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002570 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002571
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002572 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
Sven van Haastregt1006a062019-06-26 13:31:24 +00002573 if (PlaceArgs.empty()) {
2574 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2575 } else {
2576 Diag(StartLoc, diag::err_openclcxx_placement_new);
2577 }
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002578 return true;
2579 }
2580
Richard Smithb2f0f052016-10-10 18:54:32 +00002581 assert(!R.empty() && "implicitly declared allocation functions not found");
2582 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2583
2584 // We do our own custom access checks below.
2585 R.suppressDiagnostics();
2586
2587 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002588 OperatorNew, /*Candidates=*/nullptr,
2589 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002590 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002591 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002592
Richard Smithb2f0f052016-10-10 18:54:32 +00002593 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002594 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002595 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002596 return false;
2597 }
2598
Richard Smithb2f0f052016-10-10 18:54:32 +00002599 // Note, the name of OperatorNew might have been changed from array to
2600 // non-array by resolveAllocationOverload.
2601 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2602 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2603 ? OO_Array_Delete
2604 : OO_Delete);
2605
Douglas Gregor6642ca22010-02-26 05:06:18 +00002606 // C++ [expr.new]p19:
2607 //
2608 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002609 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002610 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002611 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002612 // the scope of T. If this lookup fails to find the name, or if
2613 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002614 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002615 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002616 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002617 auto *RD =
2618 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002619 LookupQualifiedName(FoundDelete, RD);
2620 }
John McCallfb6f5262010-03-18 08:19:33 +00002621 if (FoundDelete.isAmbiguous())
2622 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002623
Richard Smithb2f0f052016-10-10 18:54:32 +00002624 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002625 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002626 if (DeleteScope == AFS_Class)
2627 return true;
2628
Douglas Gregor6642ca22010-02-26 05:06:18 +00002629 DeclareGlobalNewDelete();
2630 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2631 }
2632
2633 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002634
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002635 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002636
John McCalld3be2c82010-09-14 21:34:24 +00002637 // Whether we're looking for a placement operator delete is dictated
2638 // by whether we selected a placement operator new, not by whether
2639 // we had explicit placement arguments. This matters for things like
2640 // struct A { void *operator new(size_t, int = 0); ... };
2641 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002642 //
2643 // We don't have any definition for what a "placement allocation function"
2644 // is, but we assume it's any allocation function whose
2645 // parameter-declaration-clause is anything other than (size_t).
2646 //
2647 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2648 // This affects whether an exception from the constructor of an overaligned
2649 // type uses the sized or non-sized form of aligned operator delete.
2650 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2651 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002652
2653 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002654 // C++ [expr.new]p20:
2655 // A declaration of a placement deallocation function matches the
2656 // declaration of a placement allocation function if it has the
2657 // same number of parameters and, after parameter transformations
2658 // (8.3.5), all parameter types except the first are
2659 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002660 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002661 // To perform this comparison, we compute the function type that
2662 // the deallocation function should have, and use that type both
2663 // for template argument deduction and for comparison purposes.
2664 QualType ExpectedFunctionType;
2665 {
Simon Pilgrim94885432020-03-04 11:25:34 +00002666 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002667
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002668 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002669 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002670 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2671 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002672
John McCalldb40c7f2010-12-14 08:05:40 +00002673 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002674 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002675 EPI.Variadic = Proto->isVariadic();
2676
Douglas Gregor6642ca22010-02-26 05:06:18 +00002677 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002678 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002679 }
2680
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002681 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002682 DEnd = FoundDelete.end();
2683 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002684 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002685 if (FunctionTemplateDecl *FnTmpl =
2686 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002687 // Perform template argument deduction to try to match the
2688 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002689 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002690 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2691 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002692 continue;
2693 } else
2694 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2695
Richard Smithbaa47832016-12-01 02:11:49 +00002696 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2697 ExpectedFunctionType,
2698 /*AdjustExcpetionSpec*/true),
2699 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002700 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002701 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002702
Richard Smithb2f0f052016-10-10 18:54:32 +00002703 if (getLangOpts().CUDA)
2704 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2705 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002706 // C++1y [expr.new]p22:
2707 // For a non-placement allocation function, the normal deallocation
2708 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002709 //
2710 // Per [expr.delete]p10, this lookup prefers a member operator delete
2711 // without a size_t argument, but prefers a non-member operator delete
2712 // with a size_t where possible (which it always is in this case).
2713 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2714 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2715 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2716 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2717 &BestDeallocFns);
2718 if (Selected)
2719 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2720 else {
2721 // If we failed to select an operator, all remaining functions are viable
2722 // but ambiguous.
2723 for (auto Fn : BestDeallocFns)
2724 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002725 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002726 }
2727
2728 // C++ [expr.new]p20:
2729 // [...] If the lookup finds a single matching deallocation
2730 // function, that function will be called; otherwise, no
2731 // deallocation function will be called.
2732 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002733 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002734
Richard Smithb2f0f052016-10-10 18:54:32 +00002735 // C++1z [expr.new]p23:
2736 // If the lookup finds a usual deallocation function (3.7.4.2)
2737 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002738 // as a placement deallocation function, would have been
2739 // selected as a match for the allocation function, the program
2740 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002741 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002742 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002743 UsualDeallocFnInfo Info(*this,
2744 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002745 // Core issue, per mail to core reflector, 2016-10-09:
2746 // If this is a member operator delete, and there is a corresponding
2747 // non-sized member operator delete, this isn't /really/ a sized
2748 // deallocation function, it just happens to have a size_t parameter.
2749 bool IsSizedDelete = Info.HasSizeT;
2750 if (IsSizedDelete && !FoundGlobalDelete) {
2751 auto NonSizedDelete =
2752 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2753 /*WantAlign*/Info.HasAlignValT);
2754 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2755 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2756 IsSizedDelete = false;
2757 }
2758
2759 if (IsSizedDelete) {
2760 SourceRange R = PlaceArgs.empty()
2761 ? SourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002762 : SourceRange(PlaceArgs.front()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002763 PlaceArgs.back()->getEndLoc());
Richard Smithb2f0f052016-10-10 18:54:32 +00002764 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2765 if (!OperatorDelete->isImplicit())
2766 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2767 << DeleteName;
2768 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002769 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002770
2771 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2772 Matches[0].first);
2773 } else if (!Matches.empty()) {
2774 // We found multiple suitable operators. Per [expr.new]p20, that means we
2775 // call no 'operator delete' function, but we should at least warn the user.
2776 // FIXME: Suppress this warning if the construction cannot throw.
2777 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2778 << DeleteName << AllocElemType;
2779
2780 for (auto &Match : Matches)
2781 Diag(Match.second->getLocation(),
2782 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002783 }
2784
Sebastian Redlfaf68082008-12-03 20:26:15 +00002785 return false;
2786}
2787
2788/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2789/// delete. These are:
2790/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002791/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002792/// void* operator new(std::size_t) throw(std::bad_alloc);
2793/// void* operator new[](std::size_t) throw(std::bad_alloc);
2794/// void operator delete(void *) throw();
2795/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002796/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002797/// void* operator new(std::size_t);
2798/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002799/// void operator delete(void *) noexcept;
2800/// void operator delete[](void *) noexcept;
2801/// // C++1y:
2802/// void* operator new(std::size_t);
2803/// void* operator new[](std::size_t);
2804/// void operator delete(void *) noexcept;
2805/// void operator delete[](void *) noexcept;
2806/// void operator delete(void *, std::size_t) noexcept;
2807/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002808/// @endcode
2809/// Note that the placement and nothrow forms of new are *not* implicitly
2810/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002811void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002812 if (GlobalNewDeleteDeclared)
2813 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002814
Anastasia Stulova46b55fa2019-07-18 10:02:35 +00002815 // The implicitly declared new and delete operators
2816 // are not supported in OpenCL.
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002817 if (getLangOpts().OpenCLCPlusPlus)
2818 return;
2819
Douglas Gregor87f54062009-09-15 22:30:29 +00002820 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002821 // [...] The following allocation and deallocation functions (18.4) are
2822 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002823 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002824 //
Sebastian Redl37588092011-03-14 18:08:30 +00002825 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002826 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002827 // void* operator new[](std::size_t) throw(std::bad_alloc);
2828 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002829 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002830 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002831 // void* operator new(std::size_t);
2832 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002833 // void operator delete(void*) noexcept;
2834 // void operator delete[](void*) noexcept;
2835 // C++1y:
2836 // void* operator new(std::size_t);
2837 // void* operator new[](std::size_t);
2838 // void operator delete(void*) noexcept;
2839 // void operator delete[](void*) noexcept;
2840 // void operator delete(void*, std::size_t) noexcept;
2841 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002842 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002843 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002844 // new, operator new[], operator delete, operator delete[].
2845 //
2846 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2847 // "std" or "bad_alloc" as necessary to form the exception specification.
2848 // However, we do not make these implicit declarations visible to name
2849 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002850 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002851 // The "std::bad_alloc" class has not yet been declared, so build it
2852 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002853 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2854 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002855 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002856 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002857 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002858 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002859 }
Richard Smith59139022016-09-30 22:41:36 +00002860 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002861 // The "std::align_val_t" enum class has not yet been declared, so build it
2862 // implicitly.
2863 auto *AlignValT = EnumDecl::Create(
2864 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2865 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2866 AlignValT->setIntegerType(Context.getSizeType());
2867 AlignValT->setPromotionType(Context.getSizeType());
2868 AlignValT->setImplicit(true);
2869 StdAlignValT = AlignValT;
2870 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002871
Sebastian Redlfaf68082008-12-03 20:26:15 +00002872 GlobalNewDeleteDeclared = true;
2873
2874 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2875 QualType SizeT = Context.getSizeType();
2876
Richard Smith96269c52016-09-29 22:49:46 +00002877 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2878 QualType Return, QualType Param) {
2879 llvm::SmallVector<QualType, 3> Params;
2880 Params.push_back(Param);
2881
2882 // Create up to four variants of the function (sized/aligned).
2883 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2884 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002885 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002886
2887 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2888 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2889 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002890 if (Sized)
2891 Params.push_back(SizeT);
2892
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002893 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002894 if (Aligned)
2895 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2896
2897 DeclareGlobalAllocationFunction(
2898 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2899
2900 if (Aligned)
2901 Params.pop_back();
2902 }
2903 }
2904 };
2905
2906 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2907 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2908 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2909 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002910}
2911
2912/// DeclareGlobalAllocationFunction - Declares a single implicit global
2913/// allocation function if it doesn't already exist.
2914void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002915 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002916 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002917 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2918
2919 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002920 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2921 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2922 Alloc != AllocEnd; ++Alloc) {
2923 // Only look at non-template functions, as it is the predefined,
2924 // non-templated allocation function we are trying to declare here.
2925 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002926 if (Func->getNumParams() == Params.size()) {
2927 llvm::SmallVector<QualType, 3> FuncParams;
2928 for (auto *P : Func->parameters())
2929 FuncParams.push_back(
2930 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2931 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002932 // Make the function visible to name lookup, even if we found it in
2933 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002934 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002935 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002936 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002937 }
Chandler Carruth93538422010-02-03 11:02:14 +00002938 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002939 }
2940 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002941
Erich Keane881e83d2019-03-04 14:54:52 +00002942 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
Erich Keane00022812019-05-23 16:05:21 +00002943 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
Richard Smithc015bc22014-02-07 22:39:53 +00002944
Richard Smithf8b417c2014-02-08 00:42:45 +00002945 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002946 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002947 = (Name.getCXXOverloadedOperator() == OO_New ||
2948 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002949 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002950 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002951 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002952 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002953 EPI.ExceptionSpec.Type = EST_Dynamic;
2954 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002955 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002956 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002957 EPI.ExceptionSpec =
2958 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002959 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002960
Artem Belevich07db5cf2016-10-21 20:34:05 +00002961 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2962 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2963 FunctionDecl *Alloc = FunctionDecl::Create(
2964 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2965 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2966 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002967 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002968 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002969
Petr Hosek821b38f2018-12-04 03:25:25 +00002970 Alloc->addAttr(VisibilityAttr::CreateImplicit(
2971 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2972 ? VisibilityAttr::Hidden
2973 : VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002974
Artem Belevich07db5cf2016-10-21 20:34:05 +00002975 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2976 for (QualType T : Params) {
2977 ParamDecls.push_back(ParmVarDecl::Create(
2978 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2979 /*TInfo=*/nullptr, SC_None, nullptr));
2980 ParamDecls.back()->setImplicit();
2981 }
2982 Alloc->setParams(ParamDecls);
2983 if (ExtraAttr)
2984 Alloc->addAttr(ExtraAttr);
Roman Lebedev3dd5a292020-02-26 01:37:17 +03002985 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);
Artem Belevich07db5cf2016-10-21 20:34:05 +00002986 Context.getTranslationUnitDecl()->addDecl(Alloc);
2987 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2988 };
2989
2990 if (!LangOpts.CUDA)
2991 CreateAllocationFunctionDecl(nullptr);
2992 else {
2993 // Host and device get their own declaration so each can be
2994 // defined or re-declared independently.
2995 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2996 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002997 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002998}
2999
Richard Smith1cdec012013-09-29 04:40:38 +00003000FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
3001 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00003002 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00003003 DeclarationName Name) {
3004 DeclareGlobalNewDelete();
3005
3006 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3007 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
3008
Richard Smithb2f0f052016-10-10 18:54:32 +00003009 // FIXME: It's possible for this to result in ambiguity, through a
3010 // user-declared variadic operator delete or the enable_if attribute. We
3011 // should probably not consider those cases to be usual deallocation
3012 // functions. But for now we just make an arbitrary choice in that case.
3013 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3014 Overaligned);
3015 assert(Result.FD && "operator delete missing from global scope?");
3016 return Result.FD;
3017}
Richard Smith1cdec012013-09-29 04:40:38 +00003018
Richard Smithb2f0f052016-10-10 18:54:32 +00003019FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
3020 CXXRecordDecl *RD) {
3021 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00003022
Richard Smithb2f0f052016-10-10 18:54:32 +00003023 FunctionDecl *OperatorDelete = nullptr;
3024 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3025 return nullptr;
3026 if (OperatorDelete)
3027 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00003028
Richard Smithb2f0f052016-10-10 18:54:32 +00003029 // If there's no class-specific operator delete, look up the global
3030 // non-array delete.
3031 return FindUsualDeallocationFunction(
3032 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
3033 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00003034}
3035
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003036bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3037 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00003038 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00003039 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003040 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00003041 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003042
John McCall27b18f82009-11-17 02:14:36 +00003043 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003044 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003045
Chandler Carruthb6f99172010-06-28 00:30:51 +00003046 Found.suppressDiagnostics();
3047
Richard Smithb2f0f052016-10-10 18:54:32 +00003048 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00003049
Richard Smithb2f0f052016-10-10 18:54:32 +00003050 // C++17 [expr.delete]p10:
3051 // If the deallocation functions have class scope, the one without a
3052 // parameter of type std::size_t is selected.
3053 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
3054 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
3055 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00003056
Richard Smithb2f0f052016-10-10 18:54:32 +00003057 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00003058 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00003059 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00003060
Richard Smithb2f0f052016-10-10 18:54:32 +00003061 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00003062 if (Operator->isDeleted()) {
3063 if (Diagnose) {
3064 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00003065 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00003066 }
3067 return true;
3068 }
3069
Richard Smith921bd202012-02-26 09:11:52 +00003070 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00003071 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00003072 return true;
3073
John McCall66a87592010-08-04 00:31:26 +00003074 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00003075 }
John McCall66a87592010-08-04 00:31:26 +00003076
Richard Smithb2f0f052016-10-10 18:54:32 +00003077 // We found multiple suitable operators; complain about the ambiguity.
3078 // FIXME: The standard doesn't say to do this; it appears that the intent
3079 // is that this should never happen.
3080 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00003081 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00003082 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3083 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00003084 for (auto &Match : Matches)
3085 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00003086 }
John McCall66a87592010-08-04 00:31:26 +00003087 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003088 }
3089
3090 // We did find operator delete/operator delete[] declarations, but
3091 // none of them were suitable.
3092 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00003093 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00003094 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3095 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003096
Richard Smithb2f0f052016-10-10 18:54:32 +00003097 for (NamedDecl *D : Found)
3098 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00003099 diag::note_member_declared_here) << Name;
3100 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003101 return true;
3102 }
3103
Craig Topperc3ec1492014-05-26 06:22:03 +00003104 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003105 return false;
3106}
3107
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003108namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003109/// Checks whether delete-expression, and new-expression used for
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003110/// initializing deletee have the same array form.
3111class MismatchingNewDeleteDetector {
3112public:
3113 enum MismatchResult {
3114 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3115 NoMismatch,
3116 /// Indicates that variable is initialized with mismatching form of \a new.
3117 VarInitMismatches,
3118 /// Indicates that member is initialized with mismatching form of \a new.
3119 MemberInitMismatches,
3120 /// Indicates that 1 or more constructors' definitions could not been
3121 /// analyzed, and they will be checked again at the end of translation unit.
3122 AnalyzeLater
3123 };
3124
3125 /// \param EndOfTU True, if this is the final analysis at the end of
3126 /// translation unit. False, if this is the initial analysis at the point
3127 /// delete-expression was encountered.
3128 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00003129 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003130 HasUndefinedConstructors(false) {}
3131
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003132 /// Checks whether pointee of a delete-expression is initialized with
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003133 /// matching form of new-expression.
3134 ///
3135 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3136 /// point where delete-expression is encountered, then a warning will be
3137 /// issued immediately. If return value is \c AnalyzeLater at the point where
3138 /// delete-expression is seen, then member will be analyzed at the end of
3139 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3140 /// couldn't be analyzed. If at least one constructor initializes the member
3141 /// with matching type of new, the return value is \c NoMismatch.
3142 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003143 /// Analyzes a class member.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003144 /// \param Field Class member to analyze.
3145 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3146 /// for deleting the \p Field.
3147 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00003148 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003149 /// List of mismatching new-expressions used for initialization of the pointee
3150 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3151 /// Indicates whether delete-expression was in array form.
3152 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003153
3154private:
3155 const bool EndOfTU;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003156 /// Indicates that there is at least one constructor without body.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003157 bool HasUndefinedConstructors;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003158 /// Returns \c CXXNewExpr from given initialization expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003159 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00003160 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003161 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003162 /// Returns whether member is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003163 /// \c new either by the member initializer or in-class initialization.
3164 ///
3165 /// If bodies of all constructors are not visible at the end of translation
3166 /// unit or at least one constructor initializes member with the matching
3167 /// form of \c new, mismatch cannot be proven, and this function will return
3168 /// \c NoMismatch.
3169 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003170 /// Returns whether variable is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003171 /// \c new.
3172 ///
3173 /// If variable is initialized with matching form of \c new or variable is not
3174 /// initialized with a \c new expression, this function will return true.
3175 /// If variable is initialized with mismatching form of \c new, returns false.
3176 /// \param D Variable to analyze.
3177 bool hasMatchingVarInit(const DeclRefExpr *D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003178 /// Checks whether the constructor initializes pointee with mismatching
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003179 /// form of \c new.
3180 ///
3181 /// Returns true, if member is initialized with matching form of \c new in
3182 /// member initializer list. Returns false, if member is initialized with the
3183 /// matching form of \c new in this constructor's initializer or given
3184 /// constructor isn't defined at the point where delete-expression is seen, or
3185 /// member isn't initialized by the constructor.
3186 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003187 /// Checks whether member is initialized with matching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003188 /// \c new in member initializer list.
3189 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3190 /// Checks whether member is initialized with mismatching form of \c new by
3191 /// in-class initializer.
3192 MismatchResult analyzeInClassInitializer();
3193};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003194}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003195
3196MismatchingNewDeleteDetector::MismatchResult
3197MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3198 NewExprs.clear();
3199 assert(DE && "Expected delete-expression");
3200 IsArrayForm = DE->isArrayForm();
3201 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3202 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3203 return analyzeMemberExpr(ME);
3204 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3205 if (!hasMatchingVarInit(D))
3206 return VarInitMismatches;
3207 }
3208 return NoMismatch;
3209}
3210
3211const CXXNewExpr *
3212MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3213 assert(E != nullptr && "Expected a valid initializer expression");
3214 E = E->IgnoreParenImpCasts();
3215 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3216 if (ILE->getNumInits() == 1)
3217 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3218 }
3219
3220 return dyn_cast_or_null<const CXXNewExpr>(E);
3221}
3222
3223bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3224 const CXXCtorInitializer *CI) {
3225 const CXXNewExpr *NE = nullptr;
3226 if (Field == CI->getMember() &&
3227 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3228 if (NE->isArray() == IsArrayForm)
3229 return true;
3230 else
3231 NewExprs.push_back(NE);
3232 }
3233 return false;
3234}
3235
3236bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3237 const CXXConstructorDecl *CD) {
3238 if (CD->isImplicit())
3239 return false;
3240 const FunctionDecl *Definition = CD;
3241 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3242 HasUndefinedConstructors = true;
3243 return EndOfTU;
3244 }
3245 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3246 if (hasMatchingNewInCtorInit(CI))
3247 return true;
3248 }
3249 return false;
3250}
3251
3252MismatchingNewDeleteDetector::MismatchResult
3253MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3254 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003255 const Expr *InitExpr = Field->getInClassInitializer();
3256 if (!InitExpr)
3257 return EndOfTU ? NoMismatch : AnalyzeLater;
3258 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003259 if (NE->isArray() != IsArrayForm) {
3260 NewExprs.push_back(NE);
3261 return MemberInitMismatches;
3262 }
3263 }
3264 return NoMismatch;
3265}
3266
3267MismatchingNewDeleteDetector::MismatchResult
3268MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3269 bool DeleteWasArrayForm) {
3270 assert(Field != nullptr && "Analysis requires a valid class member.");
3271 this->Field = Field;
3272 IsArrayForm = DeleteWasArrayForm;
3273 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3274 for (const auto *CD : RD->ctors()) {
3275 if (hasMatchingNewInCtor(CD))
3276 return NoMismatch;
3277 }
3278 if (HasUndefinedConstructors)
3279 return EndOfTU ? NoMismatch : AnalyzeLater;
3280 if (!NewExprs.empty())
3281 return MemberInitMismatches;
3282 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3283 : NoMismatch;
3284}
3285
3286MismatchingNewDeleteDetector::MismatchResult
3287MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3288 assert(ME != nullptr && "Expected a member expression");
3289 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3290 return analyzeField(F, IsArrayForm);
3291 return NoMismatch;
3292}
3293
3294bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3295 const CXXNewExpr *NE = nullptr;
3296 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3297 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3298 NE->isArray() != IsArrayForm) {
3299 NewExprs.push_back(NE);
3300 }
3301 }
3302 return NewExprs.empty();
3303}
3304
3305static void
3306DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3307 const MismatchingNewDeleteDetector &Detector) {
3308 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3309 FixItHint H;
3310 if (!Detector.IsArrayForm)
3311 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3312 else {
3313 SourceLocation RSquare = Lexer::findLocationAfterToken(
3314 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3315 SemaRef.getLangOpts(), true);
3316 if (RSquare.isValid())
3317 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3318 }
3319 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3320 << Detector.IsArrayForm << H;
3321
3322 for (const auto *NE : Detector.NewExprs)
3323 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3324 << Detector.IsArrayForm;
3325}
3326
3327void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3328 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3329 return;
3330 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3331 switch (Detector.analyzeDeleteExpr(DE)) {
3332 case MismatchingNewDeleteDetector::VarInitMismatches:
3333 case MismatchingNewDeleteDetector::MemberInitMismatches: {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003334 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003335 break;
3336 }
3337 case MismatchingNewDeleteDetector::AnalyzeLater: {
3338 DeleteExprs[Detector.Field].push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003339 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003340 break;
3341 }
3342 case MismatchingNewDeleteDetector::NoMismatch:
3343 break;
3344 }
3345}
3346
3347void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3348 bool DeleteWasArrayForm) {
3349 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3350 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3351 case MismatchingNewDeleteDetector::VarInitMismatches:
3352 llvm_unreachable("This analysis should have been done for class members.");
3353 case MismatchingNewDeleteDetector::AnalyzeLater:
3354 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3355 "translation unit.");
3356 case MismatchingNewDeleteDetector::MemberInitMismatches:
3357 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3358 break;
3359 case MismatchingNewDeleteDetector::NoMismatch:
3360 break;
3361 }
3362}
3363
Sebastian Redlbd150f42008-11-21 19:14:01 +00003364/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3365/// @code ::delete ptr; @endcode
3366/// or
3367/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003368ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003369Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003370 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003371 // C++ [expr.delete]p1:
3372 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003373 // non-explicit conversion function to a pointer type. The result has type
3374 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003375 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003376 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3377
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003378 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003379 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003380 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003381 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003382
John Wiegley01296292011-04-08 18:41:53 +00003383 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003384 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003385 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003386 if (Ex.isInvalid())
3387 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003388
John Wiegley01296292011-04-08 18:41:53 +00003389 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003390
Richard Smithccc11812013-05-21 19:05:48 +00003391 class DeleteConverter : public ContextualImplicitConverter {
3392 public:
3393 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003394
Craig Toppere14c0f82014-03-12 04:55:44 +00003395 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003396 // FIXME: If we have an operator T* and an operator void*, we must pick
3397 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003398 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003399 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003400 return true;
3401 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003402 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003403
Richard Smithccc11812013-05-21 19:05:48 +00003404 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003405 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003406 return S.Diag(Loc, diag::err_delete_operand) << T;
3407 }
3408
3409 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003410 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003411 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3412 }
3413
3414 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003415 QualType T,
3416 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003417 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3418 }
3419
3420 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003421 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003422 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3423 << ConvTy;
3424 }
3425
3426 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003427 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003428 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3429 }
3430
3431 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003432 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003433 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3434 << ConvTy;
3435 }
3436
3437 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003438 QualType T,
3439 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003440 llvm_unreachable("conversion functions are permitted");
3441 }
3442 } Converter;
3443
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003444 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003445 if (Ex.isInvalid())
3446 return ExprError();
3447 Type = Ex.get()->getType();
3448 if (!Converter.match(Type))
3449 // FIXME: PerformContextualImplicitConversion should return ExprError
3450 // itself in this case.
3451 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003452
Simon Pilgrime1485122019-10-17 11:12:31 +00003453 QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003454 QualType PointeeElem = Context.getBaseElementType(Pointee);
3455
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003456 if (Pointee.getAddressSpace() != LangAS::Default &&
3457 !getLangOpts().OpenCLCPlusPlus)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003458 return Diag(Ex.get()->getBeginLoc(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003459 diag::err_address_space_qualified_delete)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003460 << Pointee.getUnqualifiedType()
3461 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003462
Craig Topperc3ec1492014-05-26 06:22:03 +00003463 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003464 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003465 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003466 // effectively bans deletion of "void*". However, most compilers support
3467 // this, so we treat it as a warning unless we're in a SFINAE context.
3468 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003469 << Type << Ex.get()->getSourceRange();
Richard Sandiford4ece6f02020-03-03 11:20:57 +00003470 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3471 Pointee->isSizelessType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003472 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003473 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003474 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003475 // FIXME: This can result in errors if the definition was imported from a
3476 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003477 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003478 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003479 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3480 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3481 }
3482 }
3483
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003484 if (Pointee->isArrayType() && !ArrayForm) {
3485 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003486 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003487 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003488 ArrayForm = true;
3489 }
3490
Anders Carlssona471db02009-08-16 20:29:29 +00003491 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3492 ArrayForm ? OO_Array_Delete : OO_Delete);
3493
Eli Friedmanae4280f2011-07-26 22:25:31 +00003494 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003495 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003496 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3497 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003498 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003499
John McCall284c48f2011-01-27 09:37:56 +00003500 // If we're allocating an array of records, check whether the
3501 // usual operator delete[] has a size_t parameter.
3502 if (ArrayForm) {
3503 // If the user specifically asked to use the global allocator,
3504 // we'll need to do the lookup into the class.
3505 if (UseGlobal)
3506 UsualArrayDeleteWantsSize =
3507 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3508
3509 // Otherwise, the usual operator delete[] should be the
3510 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003511 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003512 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003513 UsualDeallocFnInfo(*this,
3514 DeclAccessPair::make(OperatorDelete, AS_public))
3515 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003516 }
3517
Richard Smitheec915d62012-02-18 04:13:32 +00003518 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003519 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003520 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003521 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003522 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3523 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003524 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003525
Nico Weber5a9259c2016-01-15 21:45:31 +00003526 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3527 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3528 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3529 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531
Richard Smithb2f0f052016-10-10 18:54:32 +00003532 if (!OperatorDelete) {
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003533 if (getLangOpts().OpenCLCPlusPlus) {
3534 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3535 return ExprError();
3536 }
3537
Richard Smithb2f0f052016-10-10 18:54:32 +00003538 bool IsComplete = isCompleteType(StartLoc, Pointee);
3539 bool CanProvideSize =
3540 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3541 Pointee.isDestructedType());
3542 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3543
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003544 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003545 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3546 Overaligned, DeleteName);
3547 }
Mike Stump11289f42009-09-09 15:08:12 +00003548
Eli Friedmanfa0df832012-02-02 03:46:19 +00003549 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003550
Richard Smith5b349582017-10-13 01:55:36 +00003551 // Check access and ambiguity of destructor if we're going to call it.
3552 // Note that this is required even for a virtual delete.
3553 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003554 if (PointeeRD) {
3555 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003556 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3557 PDiag(diag::err_access_dtor) << PointeeElem);
3558 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003559 }
3560 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003561
Akira Hatanaka71645c22018-12-21 07:05:36 +00003562 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
Richard Smith5b349582017-10-13 01:55:36 +00003563
3564 // Convert the operand to the type of the first parameter of operator
3565 // delete. This is only necessary if we selected a destroying operator
3566 // delete that we are going to call (non-virtually); converting to void*
3567 // is trivial and left to AST consumers to handle.
3568 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3569 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003570 Qualifiers Qs = Pointee.getQualifiers();
3571 if (Qs.hasCVRQualifiers()) {
3572 // Qualifiers are irrelevant to this conversion; we're only looking
3573 // for access and ambiguity.
3574 Qs.removeCVRQualifiers();
3575 QualType Unqual = Context.getPointerType(
3576 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3577 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3578 }
Richard Smith5b349582017-10-13 01:55:36 +00003579 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3580 if (Ex.isInvalid())
3581 return ExprError();
3582 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003583 }
3584
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003585 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003586 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3587 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003588 AnalyzeDeleteExprMismatch(Result);
3589 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003590}
3591
Eric Fiselierfa752f22018-03-21 19:19:48 +00003592static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3593 bool IsDelete,
3594 FunctionDecl *&Operator) {
3595
3596 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3597 IsDelete ? OO_Delete : OO_New);
3598
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003599 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003600 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3601 assert(!R.empty() && "implicitly declared allocation functions not found");
3602 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3603
3604 // We do our own custom access checks below.
3605 R.suppressDiagnostics();
3606
3607 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3608 OverloadCandidateSet Candidates(R.getNameLoc(),
3609 OverloadCandidateSet::CSK_Normal);
3610 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3611 FnOvl != FnOvlEnd; ++FnOvl) {
3612 // Even member operator new/delete are implicitly treated as
3613 // static, so don't use AddMemberCandidate.
3614 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3615
3616 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3617 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3618 /*ExplicitTemplateArgs=*/nullptr, Args,
3619 Candidates,
3620 /*SuppressUserConversions=*/false);
3621 continue;
3622 }
3623
3624 FunctionDecl *Fn = cast<FunctionDecl>(D);
3625 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3626 /*SuppressUserConversions=*/false);
3627 }
3628
3629 SourceRange Range = TheCall->getSourceRange();
3630
3631 // Do the resolution.
3632 OverloadCandidateSet::iterator Best;
3633 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3634 case OR_Success: {
3635 // Got one!
3636 FunctionDecl *FnDecl = Best->Function;
3637 assert(R.getNamingClass() == nullptr &&
3638 "class members should not be considered");
3639
3640 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3641 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3642 << (IsDelete ? 1 : 0) << Range;
3643 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3644 << R.getLookupName() << FnDecl->getSourceRange();
3645 return true;
3646 }
3647
3648 Operator = FnDecl;
3649 return false;
3650 }
3651
3652 case OR_No_Viable_Function:
David Blaikie5e328052019-05-03 00:44:50 +00003653 Candidates.NoteCandidates(
3654 PartialDiagnosticAt(R.getNameLoc(),
3655 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3656 << R.getLookupName() << Range),
3657 S, OCD_AllCandidates, Args);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003658 return true;
3659
3660 case OR_Ambiguous:
David Blaikie5e328052019-05-03 00:44:50 +00003661 Candidates.NoteCandidates(
3662 PartialDiagnosticAt(R.getNameLoc(),
3663 S.PDiag(diag::err_ovl_ambiguous_call)
3664 << R.getLookupName() << Range),
Richard Smith70f59b52019-10-23 17:54:10 -07003665 S, OCD_AmbiguousCandidates, Args);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003666 return true;
3667
3668 case OR_Deleted: {
David Blaikie5e328052019-05-03 00:44:50 +00003669 Candidates.NoteCandidates(
3670 PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3671 << R.getLookupName() << Range),
3672 S, OCD_AllCandidates, Args);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003673 return true;
3674 }
3675 }
3676 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3677}
3678
3679ExprResult
3680Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3681 bool IsDelete) {
3682 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3683 if (!getLangOpts().CPlusPlus) {
3684 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3685 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3686 << "C++";
3687 return ExprError();
3688 }
3689 // CodeGen assumes it can find the global new and delete to call,
3690 // so ensure that they are declared.
3691 DeclareGlobalNewDelete();
3692
3693 FunctionDecl *OperatorNewOrDelete = nullptr;
3694 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3695 OperatorNewOrDelete))
3696 return ExprError();
3697 assert(OperatorNewOrDelete && "should be found");
3698
Akira Hatanaka71645c22018-12-21 07:05:36 +00003699 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3700 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3701
Eric Fiselierfa752f22018-03-21 19:19:48 +00003702 TheCall->setType(OperatorNewOrDelete->getReturnType());
3703 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3704 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3705 InitializedEntity Entity =
3706 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3707 ExprResult Arg = PerformCopyInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003708 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
Eric Fiselierfa752f22018-03-21 19:19:48 +00003709 if (Arg.isInvalid())
3710 return ExprError();
3711 TheCall->setArg(i, Arg.get());
3712 }
3713 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3714 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3715 "Callee expected to be implicit cast to a builtin function pointer");
3716 Callee->setType(OperatorNewOrDelete->getType());
3717
3718 return TheCallResult;
3719}
3720
Nico Weber5a9259c2016-01-15 21:45:31 +00003721void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3722 bool IsDelete, bool CallCanBeVirtual,
3723 bool WarnOnNonAbstractTypes,
3724 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003725 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003726 return;
3727
3728 // C++ [expr.delete]p3:
3729 // In the first alternative (delete object), if the static type of the
3730 // object to be deleted is different from its dynamic type, the static
3731 // type shall be a base class of the dynamic type of the object to be
3732 // deleted and the static type shall have a virtual destructor or the
3733 // behavior is undefined.
3734 //
3735 const CXXRecordDecl *PointeeRD = dtor->getParent();
3736 // Note: a final class cannot be derived from, no issue there
3737 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3738 return;
3739
Nico Weberbf2260c2017-08-31 06:17:08 +00003740 // If the superclass is in a system header, there's nothing that can be done.
3741 // The `delete` (where we emit the warning) can be in a system header,
3742 // what matters for this warning is where the deleted type is defined.
3743 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3744 return;
3745
Brian Gesiak5488ab42019-01-11 01:54:53 +00003746 QualType ClassType = dtor->getThisType()->getPointeeType();
Nico Weber5a9259c2016-01-15 21:45:31 +00003747 if (PointeeRD->isAbstract()) {
3748 // If the class is abstract, we warn by default, because we're
3749 // sure the code has undefined behavior.
3750 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3751 << ClassType;
3752 } else if (WarnOnNonAbstractTypes) {
3753 // Otherwise, if this is not an array delete, it's a bit suspect,
3754 // but not necessarily wrong.
3755 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3756 << ClassType;
3757 }
3758 if (!IsDelete) {
3759 std::string TypeStr;
3760 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3761 Diag(DtorLoc, diag::note_delete_non_virtual)
3762 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3763 }
3764}
3765
Richard Smith03a4aa32016-06-23 19:02:52 +00003766Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3767 SourceLocation StmtLoc,
3768 ConditionKind CK) {
3769 ExprResult E =
3770 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3771 if (E.isInvalid())
3772 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003773 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3774 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003775}
3776
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003777/// Check the use of the given variable as a C++ condition in an if,
Douglas Gregor633caca2009-11-23 23:44:04 +00003778/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003779ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003780 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003781 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003782 if (ConditionVar->isInvalidDecl())
3783 return ExprError();
3784
Douglas Gregor633caca2009-11-23 23:44:04 +00003785 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003786
Douglas Gregor633caca2009-11-23 23:44:04 +00003787 // C++ [stmt.select]p2:
3788 // The declarator shall not specify a function or an array.
3789 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003790 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003791 diag::err_invalid_use_of_function_type)
3792 << ConditionVar->getSourceRange());
3793 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003794 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003795 diag::err_invalid_use_of_array_type)
3796 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003797
Richard Smith7dcd7332019-06-04 18:30:46 +00003798 ExprResult Condition = BuildDeclRefExpr(
3799 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3800 ConditionVar->getLocation());
Eli Friedman2dfa7932012-01-16 21:00:51 +00003801
Richard Smith03a4aa32016-06-23 19:02:52 +00003802 switch (CK) {
3803 case ConditionKind::Boolean:
3804 return CheckBooleanCondition(StmtLoc, Condition.get());
3805
Richard Smithb130fe72016-06-23 19:16:49 +00003806 case ConditionKind::ConstexprIf:
3807 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3808
Richard Smith03a4aa32016-06-23 19:02:52 +00003809 case ConditionKind::Switch:
3810 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003811 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003812
Richard Smith03a4aa32016-06-23 19:02:52 +00003813 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003814}
3815
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003816/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003817ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003818 // C++ 6.4p4:
3819 // The value of a condition that is an initialized declaration in a statement
3820 // other than a switch statement is the value of the declared variable
3821 // implicitly converted to type bool. If that conversion is ill-formed, the
3822 // program is ill-formed.
3823 // The value of a condition that is an expression is the value of the
3824 // expression, implicitly converted to bool.
3825 //
Richard Smithb130fe72016-06-23 19:16:49 +00003826 // FIXME: Return this value to the caller so they don't need to recompute it.
3827 llvm::APSInt Value(/*BitWidth*/1);
3828 return (IsConstexpr && !CondExpr->isValueDependent())
3829 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3830 CCEK_ConstexprIf)
3831 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003832}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003833
3834/// Helper function to determine whether this is the (deprecated) C++
3835/// conversion from a string literal to a pointer to non-const char or
3836/// non-const wchar_t (for narrow and wide string literals,
3837/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003838bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003839Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3840 // Look inside the implicit cast, if it exists.
3841 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3842 From = Cast->getSubExpr();
3843
3844 // A string literal (2.13.4) that is not a wide string literal can
3845 // be converted to an rvalue of type "pointer to char"; a wide
3846 // string literal can be converted to an rvalue of type "pointer
3847 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003848 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003849 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003850 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003851 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003852 // This conversion is considered only when there is an
3853 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003854 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3855 switch (StrLit->getKind()) {
3856 case StringLiteral::UTF8:
3857 case StringLiteral::UTF16:
3858 case StringLiteral::UTF32:
3859 // We don't allow UTF literals to be implicitly converted
3860 break;
3861 case StringLiteral::Ascii:
3862 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3863 ToPointeeType->getKind() == BuiltinType::Char_S);
3864 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003865 return Context.typesAreCompatible(Context.getWideCharType(),
3866 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003867 }
3868 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003869 }
3870
3871 return false;
3872}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003873
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003874static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003875 SourceLocation CastLoc,
3876 QualType Ty,
3877 CastKind Kind,
3878 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003879 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003880 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003881 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003882 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003883 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003884 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003885 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003886 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003887
Richard Smith72d74052013-07-20 19:41:36 +00003888 if (S.RequireNonAbstractType(CastLoc, Ty,
3889 diag::err_allocation_of_abstract_type))
3890 return ExprError();
3891
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003892 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003893 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003894
Richard Smith5179eb72016-06-28 19:03:57 +00003895 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3896 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003897 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003898 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003899
Richard Smithf8adcdc2014-07-17 05:12:35 +00003900 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003901 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003902 ConstructorArgs, HadMultipleCandidates,
3903 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3904 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003905 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003906 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003907
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003908 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003910
John McCalle3027922010-08-25 11:45:40 +00003911 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003912 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913
Richard Smithd3f2d322015-02-24 21:16:19 +00003914 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003915 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003916 return ExprError();
3917
Douglas Gregora4253922010-04-16 22:17:36 +00003918 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003919 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3920 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003921 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003922 if (Result.isInvalid())
3923 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003924 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003925 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3926 CK_UserDefinedConversion, Result.get(),
3927 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003928
Douglas Gregor668443e2011-01-20 00:18:04 +00003929 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003930 }
3931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003932}
Douglas Gregora4253922010-04-16 22:17:36 +00003933
Douglas Gregor5fb53972009-01-14 15:45:31 +00003934/// PerformImplicitConversion - Perform an implicit conversion of the
3935/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003936/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003937/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003938/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003939ExprResult
3940Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003941 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003942 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003943 CheckedConversionKind CCK) {
Richard Smith1ef75542018-06-27 20:30:34 +00003944 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3945 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3946 return From;
3947
John McCall0d1da222010-01-12 00:44:57 +00003948 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003949 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003950 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3951 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003952 if (Res.isInvalid())
3953 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003954 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003955 break;
John Wiegley01296292011-04-08 18:41:53 +00003956 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003957
Anders Carlsson110b07b2009-09-15 06:28:28 +00003958 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003959
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003960 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003961 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003962 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003963 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003964 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003965 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966
Anders Carlsson110b07b2009-09-15 06:28:28 +00003967 // If the user-defined conversion is specified by a conversion function,
3968 // the initial standard conversion sequence converts the source type to
3969 // the implicit object parameter of the conversion function.
3970 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003971 } else {
3972 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003973 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003974 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003975 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003976 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003977 // initial standard conversion sequence converts the source type to
3978 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003979 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3980 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003981 }
Richard Smith72d74052013-07-20 19:41:36 +00003982 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003983 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003984 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003985 PerformImplicitConversion(From, BeforeToType,
3986 ICS.UserDefined.Before, AA_Converting,
3987 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003988 if (Res.isInvalid())
3989 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003990 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003992
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003993 ExprResult CastArg = BuildCXXCastArgument(
3994 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3995 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3996 ICS.UserDefined.HadMultipleCandidates, From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003997
3998 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003999 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00004000
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004001 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00004002
Richard Smith1ef75542018-06-27 20:30:34 +00004003 // C++ [over.match.oper]p7:
4004 // [...] the second standard conversion sequence of a user-defined
4005 // conversion sequence is not applied.
4006 if (CCK == CCK_ForBuiltinOverloadedOp)
4007 return From;
4008
Richard Smith507840d2011-11-29 22:48:16 +00004009 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4010 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00004011 }
John McCall0d1da222010-01-12 00:44:57 +00004012
4013 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00004014 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00004015 PDiag(diag::err_typecheck_ambiguous_condition)
4016 << From->getSourceRange());
Richard Smith13fa4e22020-01-19 18:14:18 -08004017 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004018
Douglas Gregor39c16d42008-10-24 04:54:22 +00004019 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004020 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004021
4022 case ImplicitConversionSequence::BadConversion:
Anastasia Stulovafa755d32020-02-25 14:49:59 +00004023 Sema::AssignConvertType ConvTy =
4024 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4025 bool Diagnosed = DiagnoseAssignmentResult(
4026 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4027 ToType, From->getType(), From, Action);
Richard Smithe15a3702016-10-06 23:12:58 +00004028 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00004029 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004030 }
4031
4032 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004033 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004034}
4035
Richard Smith507840d2011-11-29 22:48:16 +00004036/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00004037/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00004038/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00004039/// expression. Flavor is the context in which we're performing this
4040/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00004041ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00004042Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00004043 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004044 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00004045 CheckedConversionKind CCK) {
4046 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004047
Mike Stump87c57ac2009-05-16 07:39:55 +00004048 // Overall FIXME: we are recomputing too many types here and doing far too
4049 // much extra work. What this means is that we need to keep track of more
4050 // information that is computed when we try the implicit conversion initially,
4051 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004052 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00004053
Douglas Gregor2fe98832008-11-03 19:09:14 +00004054 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00004055 // FIXME: When can ToType be a reference type?
4056 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00004057 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00004058 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00004059 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004060 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00004061 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00004062 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00004063 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00004064 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4065 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00004066 ConstructorArgs, /*HadMultipleCandidates*/ false,
4067 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4068 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00004069 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00004070 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00004071 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4072 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00004073 From, /*HadMultipleCandidates*/ false,
4074 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4075 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00004076 }
4077
Douglas Gregor980fb162010-04-29 18:24:40 +00004078 // Resolve overloaded function references.
4079 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4080 DeclAccessPair Found;
4081 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
4082 true, Found);
4083 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00004084 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00004085
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004086 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00004087 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004088
Douglas Gregor980fb162010-04-29 18:24:40 +00004089 From = FixOverloadedFunctionReference(From, Found, Fn);
4090 FromType = From->getType();
4091 }
4092
Richard Smitha23ab512013-05-23 00:30:41 +00004093 // If we're converting to an atomic type, first convert to the corresponding
4094 // non-atomic type.
4095 QualType ToAtomicType;
4096 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4097 ToAtomicType = ToType;
4098 ToType = ToAtomic->getValueType();
4099 }
4100
George Burgess IV8d141e02015-12-14 22:00:49 +00004101 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00004102 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004103 switch (SCS.First) {
4104 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00004105 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4106 FromType = FromAtomic->getValueType().getUnqualifiedType();
4107 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4108 From, /*BasePath=*/nullptr, VK_RValue);
4109 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00004110 break;
4111
Eli Friedman946b7b52012-01-24 22:51:26 +00004112 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00004113 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00004114 ExprResult FromRes = DefaultLvalueConversion(From);
4115 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004116 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00004117 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00004118 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00004119 }
John McCall34376a62010-12-04 03:47:34 +00004120
Douglas Gregor39c16d42008-10-24 04:54:22 +00004121 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00004122 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004123 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004124 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004125 break;
4126
4127 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004128 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004129 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004130 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004131 break;
4132
4133 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004134 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004135 }
4136
Richard Smith507840d2011-11-29 22:48:16 +00004137 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00004138 switch (SCS.Second) {
4139 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00004140 // C++ [except.spec]p5:
4141 // [For] assignment to and initialization of pointers to functions,
4142 // pointers to member functions, and references to functions: the
4143 // target entity shall allow at least the exceptions allowed by the
4144 // source value in the assignment or initialization.
4145 switch (Action) {
4146 case AA_Assigning:
4147 case AA_Initializing:
4148 // Note, function argument passing and returning are initialization.
4149 case AA_Passing:
4150 case AA_Returning:
4151 case AA_Sending:
4152 case AA_Passing_CFAudited:
4153 if (CheckExceptionSpecCompatibility(From, ToType))
4154 return ExprError();
4155 break;
4156
4157 case AA_Casting:
4158 case AA_Converting:
4159 // Casts and implicit conversions are not initialization, so are not
4160 // checked for exception specification mismatches.
4161 break;
4162 }
Sebastian Redl5d431642009-10-10 12:04:10 +00004163 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004164 break;
4165
4166 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004167 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00004168 if (ToType->isBooleanType()) {
4169 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4170 SCS.Second == ICK_Integral_Promotion &&
4171 "only enums with fixed underlying type can promote to bool");
4172 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004173 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004174 } else {
4175 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004176 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004177 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004178 break;
4179
4180 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004181 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004182 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004183 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004184 break;
4185
4186 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00004187 case ICK_Complex_Conversion: {
Simon Pilgrime1485122019-10-17 11:12:31 +00004188 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4189 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
John McCall8cb679e2010-11-15 09:13:47 +00004190 CastKind CK;
4191 if (FromEl->isRealFloatingType()) {
4192 if (ToEl->isRealFloatingType())
4193 CK = CK_FloatingComplexCast;
4194 else
4195 CK = CK_FloatingComplexToIntegralComplex;
4196 } else if (ToEl->isRealFloatingType()) {
4197 CK = CK_IntegralComplexToFloatingComplex;
4198 } else {
4199 CK = CK_IntegralComplexCast;
4200 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004201 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004202 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004203 break;
John McCall8cb679e2010-11-15 09:13:47 +00004204 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004205
Douglas Gregor39c16d42008-10-24 04:54:22 +00004206 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00004207 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00004208 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004209 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004210 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00004211 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004212 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004213 break;
4214
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004215 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004216 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004217 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004218 break;
4219
John McCall31168b02011-06-15 23:02:42 +00004220 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004221 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004222 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00004223 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00004224 if (Action == AA_Initializing || Action == AA_Assigning)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004225 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004226 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004227 << ToType << From->getType() << Action << From->getSourceRange()
4228 << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004229 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004230 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004231 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004232 << From->getType() << ToType << Action << From->getSourceRange()
4233 << 0;
John McCall31168b02011-06-15 23:02:42 +00004234
Douglas Gregor33823722011-06-11 01:09:30 +00004235 if (From->getType()->isObjCObjectPointerType() &&
4236 ToType->isObjCObjectPointerType())
4237 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00004238 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4239 !CheckObjCARCUnavailableWeakConversion(ToType,
4240 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00004241 if (Action == AA_Initializing)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004242 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
John McCall9c3467e2011-09-09 06:12:06 +00004243 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004244 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4245 << (Action == AA_Casting) << From->getType() << ToType
4246 << From->getSourceRange();
John McCall9c3467e2011-09-09 06:12:06 +00004247 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004248
Sven van Haastregt62364962019-12-02 14:20:15 +00004249 // Defer address space conversion to the third conversion.
4250 QualType FromPteeType = From->getType()->getPointeeType();
4251 QualType ToPteeType = ToType->getPointeeType();
4252 QualType NewToType = ToType;
4253 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4254 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4255 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4256 NewToType = Context.getAddrSpaceQualType(NewToType,
4257 FromPteeType.getAddressSpace());
4258 if (ToType->isObjCObjectPointerType())
4259 NewToType = Context.getObjCObjectPointerType(NewToType);
4260 else if (ToType->isBlockPointerType())
4261 NewToType = Context.getBlockPointerType(NewToType);
4262 else
4263 NewToType = Context.getPointerType(NewToType);
4264 }
4265
Richard Smith354abec2017-12-08 23:29:59 +00004266 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004267 CXXCastPath BasePath;
Sven van Haastregt62364962019-12-02 14:20:15 +00004268 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004269 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004270
4271 // Make sure we extend blocks if necessary.
4272 // FIXME: doing this here is really ugly.
4273 if (Kind == CK_BlockPointerToObjCPointerCast) {
4274 ExprResult E = From;
4275 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004276 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004277 }
Brian Kelley11352a82017-03-29 18:09:02 +00004278 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Sven van Haastregt62364962019-12-02 14:20:15 +00004279 CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4280 From = ImpCastExprToType(From, NewToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004281 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004282 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004285 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004286 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004287 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004288 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004289 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004290 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004291 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004292
4293 // We may not have been able to figure out what this member pointer resolved
4294 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004295 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004296 (void)isCompleteType(From->getExprLoc(), From->getType());
4297 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004298 }
David Majnemerd96b9972014-08-08 00:10:39 +00004299
Richard Smith507840d2011-11-29 22:48:16 +00004300 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004301 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004302 break;
4303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004304
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004305 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004306 // Perform half-to-boolean conversion via float.
4307 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004308 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004309 FromType = Context.FloatTy;
4310 }
4311
Richard Smith507840d2011-11-29 22:48:16 +00004312 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004313 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004314 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004315 break;
4316
Douglas Gregor88d292c2010-05-13 16:44:06 +00004317 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004318 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004319 if (CheckDerivedToBaseConversion(
4320 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4321 From->getSourceRange(), &BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004322 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004323
Richard Smith507840d2011-11-29 22:48:16 +00004324 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4325 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004326 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004327 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004328 }
4329
Douglas Gregor46188682010-05-18 22:42:18 +00004330 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004331 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004332 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004333 break;
4334
George Burgess IVdf1ed002016-01-13 01:52:39 +00004335 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004336 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004337 Expr *Elem = prepareVectorSplat(ToType, From).get();
4338 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4339 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004340 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004341 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342
Douglas Gregor46188682010-05-18 22:42:18 +00004343 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004344 // Case 1. x -> _Complex y
4345 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4346 QualType ElType = ToComplex->getElementType();
4347 bool isFloatingComplex = ElType->isRealFloatingType();
4348
4349 // x -> y
4350 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4351 // do nothing
4352 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004353 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004354 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004355 } else {
4356 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004357 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004358 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004359 }
4360 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004361 From = ImpCastExprToType(From, ToType,
4362 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004363 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004364
4365 // Case 2. _Complex x -> y
4366 } else {
Simon Pilgrim94885432020-03-04 11:25:34 +00004367 auto *FromComplex = From->getType()->castAs<ComplexType>();
John McCall8cb679e2010-11-15 09:13:47 +00004368 QualType ElType = FromComplex->getElementType();
4369 bool isFloatingComplex = ElType->isRealFloatingType();
4370
4371 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004372 From = ImpCastExprToType(From, ElType,
4373 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004374 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004375 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004376
4377 // x -> y
4378 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4379 // do nothing
4380 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004381 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004382 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004383 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004384 } else {
4385 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004386 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004387 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004388 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004389 }
4390 }
Douglas Gregor46188682010-05-18 22:42:18 +00004391 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004392
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004393 case ICK_Block_Pointer_Conversion: {
Marco Antogninid36e1302019-07-09 15:04:27 +00004394 LangAS AddrSpaceL =
Marco Antognini9eb95902019-07-17 08:52:09 +00004395 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
Marco Antogninid36e1302019-07-09 15:04:27 +00004396 LangAS AddrSpaceR =
Marco Antognini9eb95902019-07-17 08:52:09 +00004397 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4398 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4399 "Invalid cast");
Marco Antogninid36e1302019-07-09 15:04:27 +00004400 CastKind Kind =
4401 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4402 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004403 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004404 break;
4405 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004406
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004407 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004408 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004409 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004410 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4411 if (FromRes.isInvalid())
4412 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004413 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004414 assert ((ConvTy == Sema::Compatible) &&
4415 "Improper transparent union conversion");
4416 (void)ConvTy;
4417 break;
4418 }
4419
Guy Benyei259f9f42013-02-07 16:05:33 +00004420 case ICK_Zero_Event_Conversion:
Egor Churaev89831422016-12-23 14:55:49 +00004421 case ICK_Zero_Queue_Conversion:
4422 From = ImpCastExprToType(From, ToType,
Andrew Savonichevb555b762018-10-23 15:19:20 +00004423 CK_ZeroToOCLOpaqueType,
Egor Churaev89831422016-12-23 14:55:49 +00004424 From->getValueKind()).get();
4425 break;
4426
Douglas Gregor46188682010-05-18 22:42:18 +00004427 case ICK_Lvalue_To_Rvalue:
4428 case ICK_Array_To_Pointer:
4429 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004430 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004431 case ICK_Qualification:
4432 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004433 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004434 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004435 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004436 }
4437
4438 switch (SCS.Third) {
4439 case ICK_Identity:
4440 // Nothing to do.
4441 break;
4442
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004443 case ICK_Function_Conversion:
4444 // If both sides are functions (or pointers/references to them), there could
4445 // be incompatible exception declarations.
4446 if (CheckExceptionSpecCompatibility(From, ToType))
4447 return ExprError();
4448
4449 From = ImpCastExprToType(From, ToType, CK_NoOp,
4450 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4451 break;
4452
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004453 case ICK_Qualification: {
4454 // The qualification keeps the category of the inner expression, unless the
4455 // target type isn't a reference.
Anastasia Stulova04307942018-11-16 16:22:56 +00004456 ExprValueKind VK =
4457 ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4458
4459 CastKind CK = CK_NoOp;
4460
4461 if (ToType->isReferenceType() &&
4462 ToType->getPointeeType().getAddressSpace() !=
4463 From->getType().getAddressSpace())
4464 CK = CK_AddressSpaceConversion;
4465
4466 if (ToType->isPointerType() &&
4467 ToType->getPointeeType().getAddressSpace() !=
4468 From->getType()->getPointeeType().getAddressSpace())
4469 CK = CK_AddressSpaceConversion;
4470
4471 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4472 /*BasePath=*/nullptr, CCK)
4473 .get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004474
Douglas Gregore981bb02011-03-14 16:13:32 +00004475 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004476 !getLangOpts().WritableStrings) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004477 Diag(From->getBeginLoc(),
4478 getLangOpts().CPlusPlus11
4479 ? diag::ext_deprecated_string_literal_conversion
4480 : diag::warn_deprecated_string_literal_conversion)
4481 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004482 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004483
Douglas Gregor39c16d42008-10-24 04:54:22 +00004484 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004485 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004486
Douglas Gregor39c16d42008-10-24 04:54:22 +00004487 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004488 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004489 }
4490
Douglas Gregor298f43d2012-04-12 20:42:30 +00004491 // If this conversion sequence involved a scalar -> atomic conversion, perform
4492 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004493 if (!ToAtomicType.isNull()) {
4494 assert(Context.hasSameType(
4495 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4496 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004497 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004498 }
4499
Richard Smith13fa4e22020-01-19 18:14:18 -08004500 // Materialize a temporary if we're implicitly converting to a reference
4501 // type. This is not required by the C++ rules but is necessary to maintain
4502 // AST invariants.
4503 if (ToType->isReferenceType() && From->isRValue()) {
4504 ExprResult Res = TemporaryMaterializationConversion(From);
4505 if (Res.isInvalid())
4506 return ExprError();
4507 From = Res.get();
4508 }
4509
George Burgess IV8d141e02015-12-14 22:00:49 +00004510 // If this conversion sequence succeeded and involved implicitly converting a
4511 // _Nullable type to a _Nonnull one, complain.
Richard Smith1ef75542018-06-27 20:30:34 +00004512 if (!isCast(CCK))
George Burgess IV8d141e02015-12-14 22:00:49 +00004513 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004514 From->getBeginLoc());
George Burgess IV8d141e02015-12-14 22:00:49 +00004515
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004516 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004517}
4518
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004519/// Check the completeness of a type in a unary type trait.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004520///
4521/// If the particular type trait requires a complete type, tries to complete
4522/// it. If completing the type fails, a diagnostic is emitted and false
4523/// returned. If completing the type succeeds or no completion was required,
4524/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004525static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004526 SourceLocation Loc,
4527 QualType ArgTy) {
4528 // C++0x [meta.unary.prop]p3:
4529 // For all of the class templates X declared in this Clause, instantiating
4530 // that template with a template argument that is a class template
4531 // specialization may result in the implicit instantiation of the template
4532 // argument if and only if the semantics of X require that the argument
4533 // must be a complete type.
4534 // We apply this rule to all the type trait expressions used to implement
4535 // these class templates. We also try to follow any GCC documented behavior
4536 // in these expressions to ensure portability of standard libraries.
4537 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004538 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004539 // is_complete_type somewhat obviously cannot require a complete type.
4540 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004541 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004542
4543 // These traits are modeled on the type predicates in C++0x
4544 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4545 // requiring a complete type, as whether or not they return true cannot be
4546 // impacted by the completeness of the type.
4547 case UTT_IsVoid:
4548 case UTT_IsIntegral:
4549 case UTT_IsFloatingPoint:
4550 case UTT_IsArray:
4551 case UTT_IsPointer:
4552 case UTT_IsLvalueReference:
4553 case UTT_IsRvalueReference:
4554 case UTT_IsMemberFunctionPointer:
4555 case UTT_IsMemberObjectPointer:
4556 case UTT_IsEnum:
4557 case UTT_IsUnion:
4558 case UTT_IsClass:
4559 case UTT_IsFunction:
4560 case UTT_IsReference:
4561 case UTT_IsArithmetic:
4562 case UTT_IsFundamental:
4563 case UTT_IsObject:
4564 case UTT_IsScalar:
4565 case UTT_IsCompound:
4566 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004567 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004568
4569 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4570 // which requires some of its traits to have the complete type. However,
4571 // the completeness of the type cannot impact these traits' semantics, and
4572 // so they don't require it. This matches the comments on these traits in
4573 // Table 49.
4574 case UTT_IsConst:
4575 case UTT_IsVolatile:
4576 case UTT_IsSigned:
4577 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004578
4579 // This type trait always returns false, checking the type is moot.
4580 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004581 return true;
4582
David Majnemer213bea32015-11-16 06:58:51 +00004583 // C++14 [meta.unary.prop]:
4584 // If T is a non-union class type, T shall be a complete type.
4585 case UTT_IsEmpty:
4586 case UTT_IsPolymorphic:
4587 case UTT_IsAbstract:
4588 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4589 if (!RD->isUnion())
4590 return !S.RequireCompleteType(
4591 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4592 return true;
4593
4594 // C++14 [meta.unary.prop]:
4595 // If T is a class type, T shall be a complete type.
4596 case UTT_IsFinal:
4597 case UTT_IsSealed:
4598 if (ArgTy->getAsCXXRecordDecl())
4599 return !S.RequireCompleteType(
4600 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4601 return true;
4602
Richard Smithf03e9082017-06-01 00:28:16 +00004603 // C++1z [meta.unary.prop]:
4604 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004605 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004606 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004607 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004608 case UTT_IsStandardLayout:
4609 case UTT_IsPOD:
4610 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004611 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4612 // or an array of unknown bound. But GCC actually imposes the same constraints
4613 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004614 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004615 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004616 case UTT_HasNothrowConstructor:
4617 case UTT_HasNothrowCopy:
4618 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004619 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004620 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004621 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004622 case UTT_HasTrivialCopy:
4623 case UTT_HasTrivialDestructor:
4624 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004625 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4626 LLVM_FALLTHROUGH;
4627
4628 // C++1z [meta.unary.prop]:
4629 // T shall be a complete type, cv void, or an array of unknown bound.
4630 case UTT_IsDestructible:
4631 case UTT_IsNothrowDestructible:
4632 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004633 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004634 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004635 return true;
4636
4637 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004638 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004639 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004640}
4641
Joao Matosc9523d42013-03-27 01:34:16 +00004642static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4643 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004644 bool (CXXRecordDecl::*HasTrivial)() const,
4645 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004646 bool (CXXMethodDecl::*IsDesiredOp)() const)
4647{
4648 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4649 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4650 return true;
4651
4652 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4653 DeclarationNameInfo NameInfo(Name, KeyLoc);
4654 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4655 if (Self.LookupQualifiedName(Res, RD)) {
4656 bool FoundOperator = false;
4657 Res.suppressDiagnostics();
4658 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4659 Op != OpEnd; ++Op) {
4660 if (isa<FunctionTemplateDecl>(*Op))
4661 continue;
4662
4663 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4664 if((Operator->*IsDesiredOp)()) {
4665 FoundOperator = true;
Simon Pilgrim94885432020-03-04 11:25:34 +00004666 auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
Joao Matosc9523d42013-03-27 01:34:16 +00004667 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004668 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004669 return false;
4670 }
4671 }
4672 return FoundOperator;
4673 }
4674 return false;
4675}
4676
Alp Toker95e7ff22014-01-01 05:57:51 +00004677static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004678 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004679 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004680
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004681 ASTContext &C = Self.Context;
4682 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004683 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004684 // Type trait expressions corresponding to the primary type category
4685 // predicates in C++0x [meta.unary.cat].
4686 case UTT_IsVoid:
4687 return T->isVoidType();
4688 case UTT_IsIntegral:
4689 return T->isIntegralType(C);
4690 case UTT_IsFloatingPoint:
4691 return T->isFloatingType();
4692 case UTT_IsArray:
4693 return T->isArrayType();
4694 case UTT_IsPointer:
4695 return T->isPointerType();
4696 case UTT_IsLvalueReference:
4697 return T->isLValueReferenceType();
4698 case UTT_IsRvalueReference:
4699 return T->isRValueReferenceType();
4700 case UTT_IsMemberFunctionPointer:
4701 return T->isMemberFunctionPointerType();
4702 case UTT_IsMemberObjectPointer:
4703 return T->isMemberDataPointerType();
4704 case UTT_IsEnum:
4705 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004706 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004707 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004708 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004709 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004710 case UTT_IsFunction:
4711 return T->isFunctionType();
4712
4713 // Type trait expressions which correspond to the convenient composition
4714 // predicates in C++0x [meta.unary.comp].
4715 case UTT_IsReference:
4716 return T->isReferenceType();
4717 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004718 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004719 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004720 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004721 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004722 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004723 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004724 // Note: semantic analysis depends on Objective-C lifetime types to be
4725 // considered scalar types. However, such types do not actually behave
4726 // like scalar types at run time (since they may require retain/release
4727 // operations), so we report them as non-scalar.
4728 if (T->isObjCLifetimeType()) {
4729 switch (T.getObjCLifetime()) {
4730 case Qualifiers::OCL_None:
4731 case Qualifiers::OCL_ExplicitNone:
4732 return true;
4733
4734 case Qualifiers::OCL_Strong:
4735 case Qualifiers::OCL_Weak:
4736 case Qualifiers::OCL_Autoreleasing:
4737 return false;
4738 }
4739 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004740
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004741 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004742 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004743 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004744 case UTT_IsMemberPointer:
4745 return T->isMemberPointerType();
4746
4747 // Type trait expressions which correspond to the type property predicates
4748 // in C++0x [meta.unary.prop].
4749 case UTT_IsConst:
4750 return T.isConstQualified();
4751 case UTT_IsVolatile:
4752 return T.isVolatileQualified();
4753 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004754 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004755 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004756 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004757 case UTT_IsStandardLayout:
4758 return T->isStandardLayoutType();
4759 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004760 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004761 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004762 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004763 case UTT_IsEmpty:
4764 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4765 return !RD->isUnion() && RD->isEmpty();
4766 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004767 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004768 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004769 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004770 return false;
4771 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004772 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004773 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004774 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004775 case UTT_IsAggregate:
4776 // Report vector extensions and complex types as aggregates because they
4777 // support aggregate initialization. GCC mirrors this behavior for vectors
4778 // but not _Complex.
4779 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4780 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004781 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4782 // even then only when it is used with the 'interface struct ...' syntax
4783 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004784 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004785 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004786 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004787 case UTT_IsSealed:
4788 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004789 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004790 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004791 case UTT_IsSigned:
Zoe Carver511dbd82019-09-23 15:41:20 +00004792 // Enum types should always return false.
4793 // Floating points should always return true.
4794 return !T->isEnumeralType() && (T->isFloatingType() || T->isSignedIntegerType());
John Wiegley65497cc2011-04-27 23:09:49 +00004795 case UTT_IsUnsigned:
4796 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004797
4798 // Type trait expressions which query classes regarding their construction,
4799 // destruction, and copying. Rather than being based directly on the
4800 // related type predicates in the standard, they are specified by both
4801 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4802 // specifications.
4803 //
4804 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4805 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004806 //
4807 // Note that these builtins do not behave as documented in g++: if a class
4808 // has both a trivial and a non-trivial special member of a particular kind,
4809 // they return false! For now, we emulate this behavior.
4810 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4811 // does not correctly compute triviality in the presence of multiple special
4812 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004813 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004814 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4815 // If __is_pod (type) is true then the trait is true, else if type is
4816 // a cv class or union type (or array thereof) with a trivial default
4817 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004818 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004819 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004820 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4821 return RD->hasTrivialDefaultConstructor() &&
4822 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004823 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004824 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004825 // This trait is implemented by MSVC 2012 and needed to parse the
4826 // standard library headers. Specifically this is used as the logic
4827 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004828 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004829 return true;
4830 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4831 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4832 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004833 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004834 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4835 // If __is_pod (type) is true or type is a reference type then
4836 // the trait is true, else if type is a cv class or union type
4837 // with a trivial copy constructor ([class.copy]) then the trait
4838 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004839 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004840 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004841 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4842 return RD->hasTrivialCopyConstructor() &&
4843 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004844 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004845 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004846 // This trait is implemented by MSVC 2012 and needed to parse the
4847 // standard library headers. Specifically it is used as the logic
4848 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004849 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004850 return true;
4851 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4852 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4853 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004854 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004855 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4856 // If type is const qualified or is a reference type then the
4857 // trait is false. Otherwise if __is_pod (type) is true then the
4858 // trait is true, else if type is a cv class or union type with
4859 // a trivial copy assignment ([class.copy]) then the trait is
4860 // true, else it is false.
4861 // Note: the const and reference restrictions are interesting,
4862 // given that const and reference members don't prevent a class
4863 // from having a trivial copy assignment operator (but do cause
4864 // errors if the copy assignment operator is actually used, q.v.
4865 // [class.copy]p12).
4866
Richard Smith92f241f2012-12-08 02:53:02 +00004867 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004868 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004869 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004870 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004871 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4872 return RD->hasTrivialCopyAssignment() &&
4873 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004874 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004875 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004876 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004877 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004878 // C++14 [meta.unary.prop]:
4879 // For reference types, is_destructible<T>::value is true.
4880 if (T->isReferenceType())
4881 return true;
4882
4883 // Objective-C++ ARC: autorelease types don't require destruction.
4884 if (T->isObjCLifetimeType() &&
4885 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4886 return true;
4887
4888 // C++14 [meta.unary.prop]:
4889 // For incomplete types and function types, is_destructible<T>::value is
4890 // false.
4891 if (T->isIncompleteType() || T->isFunctionType())
4892 return false;
4893
Richard Smithf03e9082017-06-01 00:28:16 +00004894 // A type that requires destruction (via a non-trivial destructor or ARC
4895 // lifetime semantics) is not trivially-destructible.
4896 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4897 return false;
4898
David Majnemerac73de92015-08-11 03:03:28 +00004899 // C++14 [meta.unary.prop]:
4900 // For object types and given U equal to remove_all_extents_t<T>, if the
4901 // expression std::declval<U&>().~U() is well-formed when treated as an
4902 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4903 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4904 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4905 if (!Destructor)
4906 return false;
4907 // C++14 [dcl.fct.def.delete]p2:
4908 // A program that refers to a deleted function implicitly or
4909 // explicitly, other than to declare it, is ill-formed.
4910 if (Destructor->isDeleted())
4911 return false;
4912 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4913 return false;
4914 if (UTT == UTT_IsNothrowDestructible) {
Simon Pilgrim94885432020-03-04 11:25:34 +00004915 auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
David Majnemerac73de92015-08-11 03:03:28 +00004916 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004917 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004918 return false;
4919 }
4920 }
4921 return true;
4922
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004923 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004924 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004925 // If __is_pod (type) is true or type is a reference type
4926 // then the trait is true, else if type is a cv class or union
4927 // type (or array thereof) with a trivial destructor
4928 // ([class.dtor]) then the trait is true, else it is
4929 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004930 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004931 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004932
John McCall31168b02011-06-15 23:02:42 +00004933 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004934 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004935 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4936 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004937
Richard Smith92f241f2012-12-08 02:53:02 +00004938 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4939 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004940 return false;
4941 // TODO: Propagate nothrowness for implicitly declared special members.
4942 case UTT_HasNothrowAssign:
4943 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4944 // If type is const qualified or is a reference type then the
4945 // trait is false. Otherwise if __has_trivial_assign (type)
4946 // is true then the trait is true, else if type is a cv class
4947 // or union type with copy assignment operators that are known
4948 // not to throw an exception then the trait is true, else it is
4949 // false.
4950 if (C.getBaseElementType(T).isConstQualified())
4951 return false;
4952 if (T->isReferenceType())
4953 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004954 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004955 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004956
Joao Matosc9523d42013-03-27 01:34:16 +00004957 if (const RecordType *RT = T->getAs<RecordType>())
4958 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4959 &CXXRecordDecl::hasTrivialCopyAssignment,
4960 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4961 &CXXMethodDecl::isCopyAssignmentOperator);
4962 return false;
4963 case UTT_HasNothrowMoveAssign:
4964 // This trait is implemented by MSVC 2012 and needed to parse the
4965 // standard library headers. Specifically this is used as the logic
4966 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004967 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004968 return true;
4969
4970 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4971 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4972 &CXXRecordDecl::hasTrivialMoveAssignment,
4973 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4974 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004975 return false;
4976 case UTT_HasNothrowCopy:
4977 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4978 // If __has_trivial_copy (type) is true then the trait is true, else
4979 // if type is a cv class or union type with copy constructors that are
4980 // known not to throw an exception then the trait is true, else it is
4981 // false.
John McCall31168b02011-06-15 23:02:42 +00004982 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004983 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004984 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4985 if (RD->hasTrivialCopyConstructor() &&
4986 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004987 return true;
4988
4989 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004990 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004991 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004992 // A template constructor is never a copy constructor.
4993 // FIXME: However, it may actually be selected at the actual overload
4994 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004995 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004996 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004997 // UsingDecl itself is not a constructor
4998 if (isa<UsingDecl>(ND))
4999 continue;
5000 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005001 if (Constructor->isCopyConstructor(FoundTQs)) {
5002 FoundConstructor = true;
Simon Pilgrim94885432020-03-04 11:25:34 +00005003 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00005004 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5005 if (!CPT)
5006 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00005007 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00005008 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00005009 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00005010 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005011 }
5012 }
5013
Richard Smith938f40b2011-06-11 17:19:42 +00005014 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005015 }
5016 return false;
5017 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00005018 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005019 // If __has_trivial_constructor (type) is true then the trait is
5020 // true, else if type is a cv class or union type (or array
5021 // thereof) with a default constructor that is known not to
5022 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00005023 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005024 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00005025 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5026 if (RD->hasTrivialDefaultConstructor() &&
5027 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005028 return true;
5029
Alp Tokerb4bca412014-01-20 00:23:47 +00005030 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00005031 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00005032 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00005033 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00005034 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00005035 // UsingDecl itself is not a constructor
5036 if (isa<UsingDecl>(ND))
5037 continue;
5038 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00005039 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00005040 FoundConstructor = true;
Simon Pilgrim94885432020-03-04 11:25:34 +00005041 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00005042 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5043 if (!CPT)
5044 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00005045 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00005046 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00005047 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00005048 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00005049 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005050 }
Alp Tokerb4bca412014-01-20 00:23:47 +00005051 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005052 }
5053 return false;
5054 case UTT_HasVirtualDestructor:
5055 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5056 // If type is a class type with a virtual destructor ([class.dtor])
5057 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00005058 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00005059 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005060 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005061 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00005062
5063 // These type trait expressions are modeled on the specifications for the
5064 // Embarcadero C++0x type trait functions:
5065 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5066 case UTT_IsCompleteType:
5067 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5068 // Returns True if and only if T is a complete type at the point of the
5069 // function call.
5070 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00005071 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00005072 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005073 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005074}
Sebastian Redl5822f082009-02-07 20:10:22 +00005075
Alp Tokercbb90342013-12-13 20:49:58 +00005076static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5077 QualType RhsT, SourceLocation KeyLoc);
5078
Douglas Gregor29c42f22012-02-24 07:38:34 +00005079static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
5080 ArrayRef<TypeSourceInfo *> Args,
5081 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00005082 if (Kind <= UTT_Last)
5083 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
5084
Eric Fiselier1af6c112018-01-12 00:09:37 +00005085 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
5086 // traits to avoid duplication.
5087 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00005088 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
5089 Args[1]->getType(), RParenLoc);
5090
Douglas Gregor29c42f22012-02-24 07:38:34 +00005091 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00005092 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00005093 case clang::TT_IsConstructible:
5094 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00005095 case clang::TT_IsTriviallyConstructible: {
5096 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00005097 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00005098 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00005099 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00005100 // definition for is_constructible, as defined below, is known to call
5101 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00005102 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005103 // The predicate condition for a template specialization
5104 // is_constructible<T, Args...> shall be satisfied if and only if the
5105 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00005106 // variable t:
5107 //
5108 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00005109 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00005110
5111 // Precondition: T and all types in the parameter pack Args shall be
5112 // complete types, (possibly cv-qualified) void, or arrays of
5113 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00005114 for (const auto *TSI : Args) {
5115 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00005116 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00005117 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00005118
Simon Pilgrim75c26882016-09-30 14:25:09 +00005119 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005120 diag::err_incomplete_type_used_in_type_trait_expr))
5121 return false;
5122 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00005123
David Majnemer9658ecc2015-11-13 05:32:43 +00005124 // Make sure the first argument is not incomplete nor a function type.
5125 QualType T = Args[0]->getType();
5126 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00005127 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00005128
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00005129 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00005130 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00005131 if (RD && RD->isAbstract())
5132 return false;
5133
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005134 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
5135 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005136 ArgExprs.reserve(Args.size() - 1);
5137 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00005138 QualType ArgTy = Args[I]->getType();
5139 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5140 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005141 OpaqueArgExprs.push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005142 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
David Majnemer9658ecc2015-11-13 05:32:43 +00005143 ArgTy.getNonLValueExprType(S.Context),
5144 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00005145 }
Richard Smitha507bfc2014-07-23 20:07:08 +00005146 for (Expr &E : OpaqueArgExprs)
5147 ArgExprs.push_back(&E);
5148
Simon Pilgrim75c26882016-09-30 14:25:09 +00005149 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00005150 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005151 EnterExpressionEvaluationContext Unevaluated(
5152 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005153 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5154 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
5155 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
5156 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
5157 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005158 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005159 if (Init.Failed())
5160 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00005161
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005162 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005163 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5164 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005165
Alp Toker73287bf2014-01-20 00:24:09 +00005166 if (Kind == clang::TT_IsConstructible)
5167 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005168
Eric Fiselier1af6c112018-01-12 00:09:37 +00005169 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
5170 if (!T->isReferenceType())
5171 return false;
5172
5173 return !Init.isDirectReferenceBinding();
5174 }
5175
Alp Toker73287bf2014-01-20 00:24:09 +00005176 if (Kind == clang::TT_IsNothrowConstructible)
5177 return S.canThrow(Result.get()) == CT_Cannot;
5178
5179 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005180 // Under Objective-C ARC and Weak, if the destination has non-trivial
5181 // Objective-C lifetime, this is a non-trivial construction.
5182 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005183 return false;
5184
5185 // The initialization succeeded; now make sure there are no non-trivial
5186 // calls.
5187 return !Result.get()->hasNonTrivialCall(S.Context);
5188 }
5189
5190 llvm_unreachable("unhandled type trait");
5191 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005192 }
Alp Tokercbb90342013-12-13 20:49:58 +00005193 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00005194 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005195
Douglas Gregor29c42f22012-02-24 07:38:34 +00005196 return false;
5197}
5198
Simon Pilgrim75c26882016-09-30 14:25:09 +00005199ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5200 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005201 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00005202 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00005203
Alp Toker95e7ff22014-01-01 05:57:51 +00005204 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5205 *this, Kind, KWLoc, Args[0]->getType()))
5206 return ExprError();
5207
Douglas Gregor29c42f22012-02-24 07:38:34 +00005208 bool Dependent = false;
5209 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5210 if (Args[I]->getType()->isDependentType()) {
5211 Dependent = true;
5212 break;
5213 }
5214 }
Alp Tokercbb90342013-12-13 20:49:58 +00005215
5216 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005217 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00005218 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5219
5220 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5221 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005222}
5223
Alp Toker88f64e62013-12-13 21:19:30 +00005224ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5225 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005226 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005227 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005228 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00005229
Douglas Gregor29c42f22012-02-24 07:38:34 +00005230 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5231 TypeSourceInfo *TInfo;
5232 QualType T = GetTypeFromParser(Args[I], &TInfo);
5233 if (!TInfo)
5234 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00005235
5236 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005237 }
Alp Tokercbb90342013-12-13 20:49:58 +00005238
Douglas Gregor29c42f22012-02-24 07:38:34 +00005239 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5240}
5241
Alp Tokercbb90342013-12-13 20:49:58 +00005242static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5243 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005244 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5245 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005246
5247 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00005248 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005249 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00005250 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005251 // Base and Derived are not unions and name the same class type without
5252 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005253
John McCall388ef532011-01-28 22:02:36 +00005254 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00005255 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00005256 if (!rhsRecord || !lhsRecord) {
5257 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5258 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5259 if (!LHSObjTy || !RHSObjTy)
5260 return false;
5261
5262 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5263 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5264 if (!BaseInterface || !DerivedInterface)
5265 return false;
5266
5267 if (Self.RequireCompleteType(
5268 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5269 return false;
5270
5271 return BaseInterface->isSuperClassOf(DerivedInterface);
5272 }
John McCall388ef532011-01-28 22:02:36 +00005273
5274 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5275 == (lhsRecord == rhsRecord));
5276
Marshall Clowce781052019-05-13 19:29:23 +00005277 // Unions are never base classes, and never have base classes.
5278 // It doesn't matter if they are complete or not. See PR#41843
5279 if (lhsRecord && lhsRecord->getDecl()->isUnion())
5280 return false;
5281 if (rhsRecord && rhsRecord->getDecl()->isUnion())
5282 return false;
5283
John McCall388ef532011-01-28 22:02:36 +00005284 if (lhsRecord == rhsRecord)
Marshall Clowce781052019-05-13 19:29:23 +00005285 return true;
John McCall388ef532011-01-28 22:02:36 +00005286
5287 // C++0x [meta.rel]p2:
5288 // If Base and Derived are class types and are different types
5289 // (ignoring possible cv-qualifiers) then Derived shall be a
5290 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005291 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005292 diag::err_incomplete_type_used_in_type_trait_expr))
5293 return false;
5294
5295 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5296 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5297 }
John Wiegley65497cc2011-04-27 23:09:49 +00005298 case BTT_IsSame:
5299 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005300 case BTT_TypeCompatible: {
5301 // GCC ignores cv-qualifiers on arrays for this builtin.
5302 Qualifiers LhsQuals, RhsQuals;
5303 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5304 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5305 return Self.Context.typesAreCompatible(Lhs, Rhs);
5306 }
John Wiegley65497cc2011-04-27 23:09:49 +00005307 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005308 case BTT_IsConvertibleTo: {
5309 // C++0x [meta.rel]p4:
5310 // Given the following function prototype:
5311 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005312 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005313 // typename add_rvalue_reference<T>::type create();
5314 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005315 // the predicate condition for a template specialization
5316 // is_convertible<From, To> shall be satisfied if and only if
5317 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005318 // well-formed, including any implicit conversions to the return
5319 // type of the function:
5320 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005321 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005322 // return create<From>();
5323 // }
5324 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005325 // Access checking is performed as if in a context unrelated to To and
5326 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005327 // of the return-statement (including conversions to the return type)
5328 // is considered.
5329 //
5330 // We model the initialization as a copy-initialization of a temporary
5331 // of the appropriate type, which for this expression is identical to the
5332 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005333
5334 // Functions aren't allowed to return function or array types.
5335 if (RhsT->isFunctionType() || RhsT->isArrayType())
5336 return false;
5337
5338 // A return statement in a void function must have void type.
5339 if (RhsT->isVoidType())
5340 return LhsT->isVoidType();
5341
5342 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005343 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005344 return false;
5345
5346 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005347 if (LhsT->isObjectType() || LhsT->isFunctionType())
5348 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005349
5350 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005351 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005352 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005353 Expr::getValueKindForType(LhsT));
5354 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005355 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005356 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005357
5358 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005359 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005360 EnterExpressionEvaluationContext Unevaluated(
5361 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005362 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5363 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005364 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005365 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005366 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005367
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005368 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005369 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5370 }
Alp Toker73287bf2014-01-20 00:24:09 +00005371
David Majnemerb3d96882016-05-23 17:21:55 +00005372 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005373 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005374 case BTT_IsTriviallyAssignable: {
5375 // C++11 [meta.unary.prop]p3:
5376 // is_trivially_assignable is defined as:
5377 // is_assignable<T, U>::value is true and the assignment, as defined by
5378 // is_assignable, is known to call no operation that is not trivial
5379 //
5380 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005381 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005382 // treated as an unevaluated operand (Clause 5).
5383 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005384 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005385 // void, or arrays of unknown bound.
5386 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005387 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005388 diag::err_incomplete_type_used_in_type_trait_expr))
5389 return false;
5390 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005391 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005392 diag::err_incomplete_type_used_in_type_trait_expr))
5393 return false;
5394
5395 // cv void is never assignable.
5396 if (LhsT->isVoidType() || RhsT->isVoidType())
5397 return false;
5398
Simon Pilgrim75c26882016-09-30 14:25:09 +00005399 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005400 // declval<U>().
5401 if (LhsT->isObjectType() || LhsT->isFunctionType())
5402 LhsT = Self.Context.getRValueReferenceType(LhsT);
5403 if (RhsT->isObjectType() || RhsT->isFunctionType())
5404 RhsT = Self.Context.getRValueReferenceType(RhsT);
5405 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5406 Expr::getValueKindForType(LhsT));
5407 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5408 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005409
5410 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005411 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005412 EnterExpressionEvaluationContext Unevaluated(
5413 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005414 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005415 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005416 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5417 &Rhs);
Richard Smith1e3a8d12019-10-11 17:59:09 +00005418 if (Result.isInvalid())
5419 return false;
5420
5421 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
5422 Self.CheckUnusedVolatileAssignment(Result.get());
5423
5424 if (SFINAE.hasErrorOccurred())
Douglas Gregor1be329d2012-02-23 07:33:15 +00005425 return false;
5426
David Majnemerb3d96882016-05-23 17:21:55 +00005427 if (BTT == BTT_IsAssignable)
5428 return true;
5429
Alp Toker73287bf2014-01-20 00:24:09 +00005430 if (BTT == BTT_IsNothrowAssignable)
5431 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005432
Alp Toker73287bf2014-01-20 00:24:09 +00005433 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005434 // Under Objective-C ARC and Weak, if the destination has non-trivial
5435 // Objective-C lifetime, this is a non-trivial assignment.
5436 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005437 return false;
5438
5439 return !Result.get()->hasNonTrivialCall(Self.Context);
5440 }
5441
5442 llvm_unreachable("unhandled type trait");
5443 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005444 }
Alp Tokercbb90342013-12-13 20:49:58 +00005445 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005446 }
5447 llvm_unreachable("Unknown type trait or not implemented");
5448}
5449
John Wiegley6242b6a2011-04-28 00:16:57 +00005450ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5451 SourceLocation KWLoc,
5452 ParsedType Ty,
5453 Expr* DimExpr,
5454 SourceLocation RParen) {
5455 TypeSourceInfo *TSInfo;
5456 QualType T = GetTypeFromParser(Ty, &TSInfo);
5457 if (!TSInfo)
5458 TSInfo = Context.getTrivialTypeSourceInfo(T);
5459
5460 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5461}
5462
5463static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5464 QualType T, Expr *DimExpr,
5465 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005466 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005467
5468 switch(ATT) {
5469 case ATT_ArrayRank:
5470 if (T->isArrayType()) {
5471 unsigned Dim = 0;
5472 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5473 ++Dim;
5474 T = AT->getElementType();
5475 }
5476 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005477 }
John Wiegleyd3522222011-04-28 02:06:46 +00005478 return 0;
5479
John Wiegley6242b6a2011-04-28 00:16:57 +00005480 case ATT_ArrayExtent: {
5481 llvm::APSInt Value;
5482 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005483 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005484 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005485 false).isInvalid())
5486 return 0;
5487 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005488 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5489 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005490 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005491 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005492 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005493
5494 if (T->isArrayType()) {
5495 unsigned D = 0;
5496 bool Matched = false;
5497 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5498 if (Dim == D) {
5499 Matched = true;
5500 break;
5501 }
5502 ++D;
5503 T = AT->getElementType();
5504 }
5505
John Wiegleyd3522222011-04-28 02:06:46 +00005506 if (Matched && T->isArrayType()) {
5507 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5508 return CAT->getSize().getLimitedValue();
5509 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005510 }
John Wiegleyd3522222011-04-28 02:06:46 +00005511 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005512 }
5513 }
5514 llvm_unreachable("Unknown type trait or not implemented");
5515}
5516
5517ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5518 SourceLocation KWLoc,
5519 TypeSourceInfo *TSInfo,
5520 Expr* DimExpr,
5521 SourceLocation RParen) {
5522 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005523
Chandler Carruthc5276e52011-05-01 08:48:21 +00005524 // FIXME: This should likely be tracked as an APInt to remove any host
5525 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005526 uint64_t Value = 0;
5527 if (!T->isDependentType())
5528 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5529
Chandler Carruthc5276e52011-05-01 08:48:21 +00005530 // While the specification for these traits from the Embarcadero C++
5531 // compiler's documentation says the return type is 'unsigned int', Clang
5532 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5533 // compiler, there is no difference. On several other platforms this is an
5534 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005535 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5536 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005537}
5538
John Wiegleyf9f65842011-04-25 06:54:41 +00005539ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005540 SourceLocation KWLoc,
5541 Expr *Queried,
5542 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005543 // If error parsing the expression, ignore.
5544 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005545 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005546
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005547 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005548
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005549 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005550}
5551
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005552static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5553 switch (ET) {
5554 case ET_IsLValueExpr: return E->isLValue();
5555 case ET_IsRValueExpr: return E->isRValue();
5556 }
5557 llvm_unreachable("Expression trait not covered by switch");
5558}
5559
John Wiegleyf9f65842011-04-25 06:54:41 +00005560ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005561 SourceLocation KWLoc,
5562 Expr *Queried,
5563 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005564 if (Queried->isTypeDependent()) {
5565 // Delay type-checking for type-dependent expressions.
5566 } else if (Queried->getType()->isPlaceholderType()) {
5567 ExprResult PE = CheckPlaceholderExpr(Queried);
5568 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005569 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005570 }
5571
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005572 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005573
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005574 return new (Context)
5575 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005576}
5577
Richard Trieu82402a02011-09-15 21:56:47 +00005578QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005579 ExprValueKind &VK,
5580 SourceLocation Loc,
5581 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005582 assert(!LHS.get()->getType()->isPlaceholderType() &&
5583 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005584 "placeholders should have been weeded out by now");
5585
Richard Smith4baaa5a2016-12-03 01:14:32 +00005586 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5587 // temporary materialization conversion otherwise.
5588 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005589 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005590 else if (LHS.get()->isRValue())
5591 LHS = TemporaryMaterializationConversion(LHS.get());
5592 if (LHS.isInvalid())
5593 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005594
5595 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005596 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005597 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005598
Sebastian Redl5822f082009-02-07 20:10:22 +00005599 const char *OpSpelling = isIndirect ? "->*" : ".*";
5600 // C++ 5.5p2
5601 // The binary operator .* [p3: ->*] binds its second operand, which shall
5602 // be of type "pointer to member of T" (where T is a completely-defined
5603 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005604 QualType RHSType = RHS.get()->getType();
5605 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005606 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005607 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005608 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005609 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005610 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005611
Sebastian Redl5822f082009-02-07 20:10:22 +00005612 QualType Class(MemPtr->getClass(), 0);
5613
Douglas Gregord07ba342010-10-13 20:41:14 +00005614 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5615 // member pointer points must be completely-defined. However, there is no
5616 // reason for this semantic distinction, and the rule is not enforced by
5617 // other compilers. Therefore, we do not check this property, as it is
5618 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005619
Sebastian Redl5822f082009-02-07 20:10:22 +00005620 // C++ 5.5p2
5621 // [...] to its first operand, which shall be of class T or of a class of
5622 // which T is an unambiguous and accessible base class. [p3: a pointer to
5623 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005624 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005625 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005626 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5627 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005628 else {
5629 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005630 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005631 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005632 return QualType();
5633 }
5634 }
5635
Richard Trieu82402a02011-09-15 21:56:47 +00005636 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005637 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005638 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5639 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005640 return QualType();
5641 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005642
Richard Smith0f59cb32015-12-18 21:45:41 +00005643 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005644 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005645 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005646 return QualType();
5647 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005648
5649 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005650 if (CheckDerivedToBaseConversion(
5651 LHSType, Class, Loc,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005652 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005653 &BasePath))
Richard Smithdb05cd32013-12-12 03:40:18 +00005654 return QualType();
5655
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005656 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005657 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5658 if (isIndirect)
5659 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005660 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005661 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005662 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005663 }
5664
Richard Trieu82402a02011-09-15 21:56:47 +00005665 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005666 // Diagnose use of pointer-to-member type which when used as
5667 // the functional cast in a pointer-to-member expression.
5668 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5669 return QualType();
5670 }
John McCall7decc9e2010-11-18 06:31:45 +00005671
Sebastian Redl5822f082009-02-07 20:10:22 +00005672 // C++ 5.5p2
5673 // The result is an object or a function of the type specified by the
5674 // second operand.
5675 // The cv qualifiers are the union of those in the pointer and the left side,
5676 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005677 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005678 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005679
Douglas Gregor1d042092011-01-26 16:40:18 +00005680 // C++0x [expr.mptr.oper]p6:
5681 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005682 // ill-formed if the second operand is a pointer to member function with
5683 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5684 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005685 // is a pointer to member function with ref-qualifier &&.
5686 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5687 switch (Proto->getRefQualifier()) {
5688 case RQ_None:
5689 // Do nothing
5690 break;
5691
5692 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005693 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
Nicolas Lesser1ad0e9f2018-07-13 16:27:45 +00005694 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5695 // is (exactly) 'const'.
5696 if (Proto->isConst() && !Proto->isVolatile())
Richard Smith25923272017-08-25 01:47:55 +00005697 Diag(Loc, getLangOpts().CPlusPlus2a
5698 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5699 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5700 else
5701 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5702 << RHSType << 1 << LHS.get()->getSourceRange();
5703 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005704 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005705
Douglas Gregor1d042092011-01-26 16:40:18 +00005706 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005707 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005708 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005709 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005710 break;
5711 }
5712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005713
John McCall7decc9e2010-11-18 06:31:45 +00005714 // C++ [expr.mptr.oper]p6:
5715 // The result of a .* expression whose second operand is a pointer
5716 // to a data member is of the same value category as its
5717 // first operand. The result of a .* expression whose second
5718 // operand is a pointer to a member function is a prvalue. The
5719 // result of an ->* expression is an lvalue if its second operand
5720 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005721 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005722 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005723 return Context.BoundMemberTy;
5724 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005725 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005726 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005727 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005728 }
John McCall7decc9e2010-11-18 06:31:45 +00005729
Sebastian Redl5822f082009-02-07 20:10:22 +00005730 return Result;
5731}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005732
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005733/// Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005734///
5735/// This is part of the parameter validation for the ? operator. If either
5736/// value operand is a class type, the two operands are attempted to be
5737/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005738/// It returns true if the program is ill-formed and has already been diagnosed
5739/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005740static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5741 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005742 bool &HaveConversion,
5743 QualType &ToType) {
5744 HaveConversion = false;
5745 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005746
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005747 InitializationKind Kind =
5748 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005749 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005750 // The process for determining whether an operand expression E1 of type T1
5751 // can be converted to match an operand expression E2 of type T2 is defined
5752 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005753 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5754 // implicitly converted to type "lvalue reference to T2", subject to the
5755 // constraint that in the conversion the reference must bind directly to
5756 // an lvalue.
5757 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005758 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005759 // the constraint that the reference must bind directly.
5760 if (To->isLValue() || To->isXValue()) {
5761 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5762 : Self.Context.getRValueReferenceType(ToType);
5763
Douglas Gregor838fcc32010-03-26 20:14:36 +00005764 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005766 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005767 if (InitSeq.isDirectReferenceBinding()) {
5768 ToType = T;
5769 HaveConversion = true;
5770 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005771 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005772
Douglas Gregor838fcc32010-03-26 20:14:36 +00005773 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005774 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005775 }
John McCall65eb8792010-02-25 01:37:24 +00005776
Sebastian Redl1a99f442009-04-16 17:51:27 +00005777 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5778 // -- if E1 and E2 have class type, and the underlying class types are
5779 // the same or one is a base class of the other:
5780 QualType FTy = From->getType();
5781 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005782 const RecordType *FRec = FTy->getAs<RecordType>();
5783 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005784 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005785 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5786 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5787 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005788 // E1 can be converted to match E2 if the class of T2 is the
5789 // same type as, or a base class of, the class of T1, and
5790 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005791 if (FRec == TRec || FDerivedFromT) {
5792 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005793 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005794 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005795 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005796 HaveConversion = true;
5797 return false;
5798 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005799
Douglas Gregor838fcc32010-03-26 20:14:36 +00005800 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005801 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005802 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005804
Douglas Gregor838fcc32010-03-26 20:14:36 +00005805 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005807
Douglas Gregor838fcc32010-03-26 20:14:36 +00005808 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5809 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005810 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005811 // an rvalue).
5812 //
5813 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5814 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005815 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005816
Douglas Gregor838fcc32010-03-26 20:14:36 +00005817 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005818 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005819 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005820 ToType = TTy;
5821 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005822 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005823
Sebastian Redl1a99f442009-04-16 17:51:27 +00005824 return false;
5825}
5826
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005827/// Try to find a common type for two according to C++0x 5.16p5.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005828///
5829/// This is part of the parameter validation for the ? operator. If either
5830/// value operand is a class type, overload resolution is used to find a
5831/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005832static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005833 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005834 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005835 OverloadCandidateSet CandidateSet(QuestionLoc,
5836 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005837 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005838 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005839
5840 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005841 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005842 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005843 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005844 ExprResult LHSRes = Self.PerformImplicitConversion(
5845 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5846 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005847 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005848 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005849 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005850
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005851 ExprResult RHSRes = Self.PerformImplicitConversion(
5852 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5853 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005854 if (RHSRes.isInvalid())
5855 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005856 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005857 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005858 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005859 return false;
John Wiegley01296292011-04-08 18:41:53 +00005860 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005861
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005862 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005863
5864 // Emit a better diagnostic if one of the expressions is a null pointer
5865 // constant and the other is a pointer type. In this case, the user most
5866 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005867 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005868 return true;
5869
5870 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005871 << LHS.get()->getType() << RHS.get()->getType()
5872 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005873 return true;
5874
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005875 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005876 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005877 << LHS.get()->getType() << RHS.get()->getType()
5878 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005879 // FIXME: Print the possible common types by printing the return types of
5880 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005881 break;
5882
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005883 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005884 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005885 }
5886 return true;
5887}
5888
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005889/// Perform an "extended" implicit conversion as returned by
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005890/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005891static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005892 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005893 InitializationKind Kind =
5894 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005895 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005896 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005897 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005898 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005899 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005900
John Wiegley01296292011-04-08 18:41:53 +00005901 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005902 return false;
5903}
5904
Erich Keane349636d2019-12-05 06:17:39 -08005905// Check the condition operand of ?: to see if it is valid for the GCC
5906// extension.
5907static bool isValidVectorForConditionalCondition(ASTContext &Ctx,
5908 QualType CondTy) {
5909 if (!CondTy->isVectorType() || CondTy->isExtVectorType())
5910 return false;
5911 const QualType EltTy =
5912 cast<VectorType>(CondTy.getCanonicalType())->getElementType();
5913
5914 assert(!EltTy->isBooleanType() && !EltTy->isEnumeralType() &&
5915 "Vectors cant be boolean or enum types");
5916 return EltTy->isIntegralType(Ctx);
5917}
5918
5919QualType Sema::CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
5920 ExprResult &RHS,
5921 SourceLocation QuestionLoc) {
5922 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5923 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5924
5925 QualType CondType = Cond.get()->getType();
Simon Pilgrim94885432020-03-04 11:25:34 +00005926 const auto *CondVT = CondType->castAs<VectorType>();
Erich Keane349636d2019-12-05 06:17:39 -08005927 QualType CondElementTy = CondVT->getElementType();
5928 unsigned CondElementCount = CondVT->getNumElements();
5929 QualType LHSType = LHS.get()->getType();
5930 const auto *LHSVT = LHSType->getAs<VectorType>();
5931 QualType RHSType = RHS.get()->getType();
5932 const auto *RHSVT = RHSType->getAs<VectorType>();
5933
5934 QualType ResultType;
5935
5936 // FIXME: In the future we should define what the Extvector conditional
5937 // operator looks like.
5938 if (LHSVT && isa<ExtVectorType>(LHSVT)) {
5939 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5940 << /*isExtVector*/ true << LHSType;
5941 return {};
5942 }
5943
5944 if (RHSVT && isa<ExtVectorType>(RHSVT)) {
5945 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5946 << /*isExtVector*/ true << RHSType;
5947 return {};
5948 }
5949
5950 if (LHSVT && RHSVT) {
5951 // If both are vector types, they must be the same type.
5952 if (!Context.hasSameType(LHSType, RHSType)) {
5953 Diag(QuestionLoc, diag::err_conditional_vector_mismatched_vectors)
5954 << LHSType << RHSType;
5955 return {};
5956 }
5957 ResultType = LHSType;
5958 } else if (LHSVT || RHSVT) {
5959 ResultType = CheckVectorOperands(
5960 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
5961 /*AllowBoolConversions*/ false);
5962 if (ResultType.isNull())
5963 return {};
5964 } else {
5965 // Both are scalar.
5966 QualType ResultElementTy;
5967 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
5968 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
5969
5970 if (Context.hasSameType(LHSType, RHSType))
5971 ResultElementTy = LHSType;
5972 else
5973 ResultElementTy =
5974 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
5975
5976 if (ResultElementTy->isEnumeralType()) {
5977 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5978 << /*isExtVector*/ false << ResultElementTy;
5979 return {};
5980 }
5981 ResultType = Context.getVectorType(
Simon Pilgrim94885432020-03-04 11:25:34 +00005982 ResultElementTy, CondType->castAs<VectorType>()->getNumElements(),
Erich Keane349636d2019-12-05 06:17:39 -08005983 VectorType::GenericVector);
5984
5985 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
5986 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
5987 }
5988
5989 assert(!ResultType.isNull() && ResultType->isVectorType() &&
5990 "Result should have been a vector type");
Simon Pilgrim94885432020-03-04 11:25:34 +00005991 auto *ResultVectorTy = ResultType->castAs<VectorType>();
5992 QualType ResultElementTy = ResultVectorTy->getElementType();
5993 unsigned ResultElementCount = ResultVectorTy->getNumElements();
Erich Keane349636d2019-12-05 06:17:39 -08005994
5995 if (ResultElementCount != CondElementCount) {
5996 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
5997 << ResultType;
5998 return {};
5999 }
6000
6001 if (Context.getTypeSize(ResultElementTy) !=
6002 Context.getTypeSize(CondElementTy)) {
6003 Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6004 << ResultType;
6005 return {};
6006 }
6007
6008 return ResultType;
6009}
6010
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006011/// Check the operands of ?: under C++ semantics.
Sebastian Redl1a99f442009-04-16 17:51:27 +00006012///
6013/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
6014/// extension. In this case, LHS == Cond. (But they're not aliases.)
Erich Keane349636d2019-12-05 06:17:39 -08006015///
6016/// This function also implements GCC's vector extension for conditionals.
6017/// GCC's vector extension permits the use of a?b:c where the type of
6018/// a is that of a integer vector with the same number of elements and
6019/// size as the vectors of b and c. If one of either b or c is a scalar
6020/// it is implicitly converted to match the type of the vector.
6021/// Otherwise the expression is ill-formed. If both b and c are scalars,
6022/// then b and c are checked and converted to the type of a if possible.
6023/// Unlike the OpenCL ?: operator, the expression is evaluated as
6024/// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
Richard Smithf2b084f2012-08-08 06:13:49 +00006025QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6026 ExprResult &RHS, ExprValueKind &VK,
6027 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00006028 SourceLocation QuestionLoc) {
Erich Keane349636d2019-12-05 06:17:39 -08006029 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6030 // pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00006031
John McCall7decc9e2010-11-18 06:31:45 +00006032 // Assume r-value.
6033 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00006034 OK = OK_Ordinary;
Erich Keane349636d2019-12-05 06:17:39 -08006035 bool IsVectorConditional =
6036 isValidVectorForConditionalCondition(Context, Cond.get()->getType());
6037
6038 // C++11 [expr.cond]p1
6039 // The first expression is contextually converted to bool.
6040 if (!Cond.get()->isTypeDependent()) {
6041 ExprResult CondRes = IsVectorConditional
6042 ? DefaultFunctionArrayLvalueConversion(Cond.get())
6043 : CheckCXXBooleanCondition(Cond.get());
6044 if (CondRes.isInvalid())
6045 return QualType();
6046 Cond = CondRes;
6047 } else {
6048 // To implement C++, the first expression typically doesn't alter the result
6049 // type of the conditional, however the GCC compatible vector extension
6050 // changes the result type to be that of the conditional. Since we cannot
6051 // know if this is a vector extension here, delay the conversion of the
6052 // LHS/RHS below until later.
6053 return Context.DependentTy;
6054 }
6055
John McCall7decc9e2010-11-18 06:31:45 +00006056
Sebastian Redl1a99f442009-04-16 17:51:27 +00006057 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00006058 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00006059 return Context.DependentTy;
6060
Richard Smith45edb702012-08-07 22:06:48 +00006061 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00006062 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00006063 QualType LTy = LHS.get()->getType();
6064 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006065 bool LVoid = LTy->isVoidType();
6066 bool RVoid = RTy->isVoidType();
6067 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006068 // ... one of the following shall hold:
6069 // -- The second or the third operand (but not both) is a (possibly
6070 // parenthesized) throw-expression; the result is of the type
6071 // and value category of the other.
6072 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6073 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
Erich Keane349636d2019-12-05 06:17:39 -08006074
6075 // Void expressions aren't legal in the vector-conditional expressions.
6076 if (IsVectorConditional) {
6077 SourceRange DiagLoc =
6078 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6079 bool IsThrow = LVoid ? LThrow : RThrow;
6080 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6081 << DiagLoc << IsThrow;
6082 return QualType();
6083 }
6084
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006085 if (LThrow != RThrow) {
6086 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6087 VK = NonThrow->getValueKind();
6088 // DR (no number yet): the result is a bit-field if the
6089 // non-throw-expression operand is a bit-field.
6090 OK = NonThrow->getObjectKind();
6091 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00006092 }
6093
Sebastian Redl1a99f442009-04-16 17:51:27 +00006094 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00006095 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00006096 if (LVoid && RVoid)
6097 return Context.VoidTy;
6098
6099 // Neither holds, error.
6100 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6101 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00006102 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006103 return QualType();
6104 }
6105
6106 // Neither is void.
Erich Keane349636d2019-12-05 06:17:39 -08006107 if (IsVectorConditional)
6108 return CheckGNUVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
Sebastian Redl1a99f442009-04-16 17:51:27 +00006109
Richard Smithf2b084f2012-08-08 06:13:49 +00006110 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00006111 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00006112 // either has (cv) class type [...] an attempt is made to convert each of
6113 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006114 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00006115 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006116 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00006117 QualType L2RType, R2LType;
6118 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00006119 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00006120 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00006121 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00006122 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006123
Sebastian Redl1a99f442009-04-16 17:51:27 +00006124 // If both can be converted, [...] the program is ill-formed.
6125 if (HaveL2R && HaveR2L) {
6126 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00006127 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006128 return QualType();
6129 }
6130
6131 // If exactly one conversion is possible, that conversion is applied to
6132 // the chosen operand and the converted operands are used in place of the
6133 // original operands for the remainder of this section.
6134 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00006135 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00006136 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00006137 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006138 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00006139 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00006140 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00006141 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006142 }
6143 }
6144
Richard Smithf2b084f2012-08-08 06:13:49 +00006145 // C++11 [expr.cond]p3
6146 // if both are glvalues of the same value category and the same type except
6147 // for cv-qualification, an attempt is made to convert each of those
6148 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00006149 // FIXME:
6150 // Resolving a defect in P0012R1: we extend this to cover all cases where
6151 // one of the operands is reference-compatible with the other, in order
Richard Smith3ced2392019-12-18 14:01:40 -08006152 // to support conditionals between functions differing in noexcept. This
6153 // will similarly cover difference in array bounds after P0388R4.
Richard Smithf041e9a2020-01-09 15:31:56 -08006154 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6155 // that instead?
Richard Smithf2b084f2012-08-08 06:13:49 +00006156 ExprValueKind LVK = LHS.get()->getValueKind();
6157 ExprValueKind RVK = RHS.get()->getValueKind();
6158 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00006159 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00006160 // DerivedToBase was already handled by the class-specific case above.
6161 // FIXME: Should we allow ObjC conversions here?
Richard Smith3ced2392019-12-18 14:01:40 -08006162 const ReferenceConversions AllowedConversions =
Richard Smithf041e9a2020-01-09 15:31:56 -08006163 ReferenceConversions::Qualification |
6164 ReferenceConversions::NestedQualification |
6165 ReferenceConversions::Function;
Richard Smith3ced2392019-12-18 14:01:40 -08006166
6167 ReferenceConversions RefConv;
6168 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6169 Ref_Compatible &&
6170 !(RefConv & ~AllowedConversions) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00006171 // [...] subject to the constraint that the reference must bind
6172 // directly [...]
Peter Collingbourne766f1582019-10-19 00:34:54 +00006173 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006174 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00006175 RTy = RHS.get()->getType();
Richard Smith3ced2392019-12-18 14:01:40 -08006176 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6177 Ref_Compatible &&
6178 !(RefConv & ~AllowedConversions) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00006179 !LHS.get()->refersToBitField() &&
6180 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00006181 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6182 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006183 }
6184 }
6185
6186 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00006187 // If the second and third operands are glvalues of the same value
6188 // category and have the same type, the result is of that type and
6189 // value category and it is a bit-field if the second or the third
6190 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00006191 // We only extend this to bitfields, not to the crazy other kinds of
6192 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00006193 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00006194 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00006195 LHS.get()->isOrdinaryOrBitFieldObject() &&
6196 RHS.get()->isOrdinaryOrBitFieldObject()) {
6197 VK = LHS.get()->getValueKind();
6198 if (LHS.get()->getObjectKind() == OK_BitField ||
6199 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00006200 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006201
6202 // If we have function pointer types, unify them anyway to unify their
6203 // exception specifications, if any.
6204 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6205 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00006206 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006207 /*ConvertArgs*/false);
6208 LTy = Context.getQualifiedType(LTy, Qs);
6209
6210 assert(!LTy.isNull() && "failed to find composite pointer type for "
6211 "canonically equivalent function ptr types");
6212 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
6213 }
6214
John McCall7decc9e2010-11-18 06:31:45 +00006215 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00006216 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00006217
Richard Smithf2b084f2012-08-08 06:13:49 +00006218 // C++11 [expr.cond]p5
6219 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00006220 // do not have the same type, and either has (cv) class type, ...
6221 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6222 // ... overload resolution is used to determine the conversions (if any)
6223 // to be applied to the operands. If the overload resolution fails, the
6224 // program is ill-formed.
6225 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6226 return QualType();
6227 }
6228
Richard Smithf2b084f2012-08-08 06:13:49 +00006229 // C++11 [expr.cond]p6
6230 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00006231 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006232 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6233 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00006234 if (LHS.isInvalid() || RHS.isInvalid())
6235 return QualType();
6236 LTy = LHS.get()->getType();
6237 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006238
6239 // After those conversions, one of the following shall hold:
6240 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00006241 // is of that type. If the operands have class type, the result
6242 // is a prvalue temporary of the result type, which is
6243 // copy-initialized from either the second operand or the third
6244 // operand depending on the value of the first operand.
6245 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
6246 if (LTy->isRecordType()) {
6247 // The operands have class type. Make a temporary copy.
6248 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00006249
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006250 ExprResult LHSCopy = PerformCopyInitialization(Entity,
6251 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00006252 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00006253 if (LHSCopy.isInvalid())
6254 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006255
6256 ExprResult RHSCopy = PerformCopyInitialization(Entity,
6257 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00006258 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00006259 if (RHSCopy.isInvalid())
6260 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006261
John Wiegley01296292011-04-08 18:41:53 +00006262 LHS = LHSCopy;
6263 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00006264 }
6265
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006266 // If we have function pointer types, unify them anyway to unify their
6267 // exception specifications, if any.
6268 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6269 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
6270 assert(!LTy.isNull() && "failed to find composite pointer type for "
6271 "canonically equivalent function ptr types");
6272 }
6273
Sebastian Redl1a99f442009-04-16 17:51:27 +00006274 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00006275 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00006276
Douglas Gregor46188682010-05-18 22:42:18 +00006277 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006278 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00006279 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6280 /*AllowBothBool*/true,
6281 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00006282
Sebastian Redl1a99f442009-04-16 17:51:27 +00006283 // -- The second and third operands have arithmetic or enumeration type;
6284 // the usual arithmetic conversions are performed to bring them to a
6285 // common type, and the result is of that type.
6286 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Richard Smith4b002992019-12-16 15:17:24 -08006287 QualType ResTy =
6288 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
John Wiegley01296292011-04-08 18:41:53 +00006289 if (LHS.isInvalid() || RHS.isInvalid())
6290 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006291 if (ResTy.isNull()) {
6292 Diag(QuestionLoc,
6293 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6294 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6295 return QualType();
6296 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006297
6298 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6299 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6300
6301 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006302 }
6303
6304 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00006305 // type and the other is a null pointer constant, or both are null
6306 // pointer constants, at least one of which is non-integral; pointer
6307 // conversions and qualification conversions are performed to bring them
6308 // to their composite pointer type. The result is of the composite
6309 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00006310 // -- The second and third operands have pointer to member type, or one has
6311 // pointer to member type and the other is a null pointer constant;
6312 // pointer to member conversions and qualification conversions are
6313 // performed to bring them to a common type, whose cv-qualification
6314 // shall match the cv-qualification of either the second or the third
6315 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00006316 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6317 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006318 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006319
Douglas Gregor697a3912010-04-01 22:47:07 +00006320 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00006321 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6322 if (!Composite.isNull())
6323 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006324
Chandler Carruth9c9127e2011-02-19 00:13:59 +00006325 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00006326 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00006327 return QualType();
6328
Sebastian Redl1a99f442009-04-16 17:51:27 +00006329 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00006330 << LHS.get()->getType() << RHS.get()->getType()
6331 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006332 return QualType();
6333}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006334
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006335static FunctionProtoType::ExceptionSpecInfo
6336mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
6337 FunctionProtoType::ExceptionSpecInfo ESI2,
6338 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6339 ExceptionSpecificationType EST1 = ESI1.Type;
6340 ExceptionSpecificationType EST2 = ESI2.Type;
6341
6342 // If either of them can throw anything, that is the result.
6343 if (EST1 == EST_None) return ESI1;
6344 if (EST2 == EST_None) return ESI2;
6345 if (EST1 == EST_MSAny) return ESI1;
6346 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006347 if (EST1 == EST_NoexceptFalse) return ESI1;
6348 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006349
6350 // If either of them is non-throwing, the result is the other.
Erich Keaned02f4a12019-05-30 17:31:54 +00006351 if (EST1 == EST_NoThrow) return ESI2;
6352 if (EST2 == EST_NoThrow) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006353 if (EST1 == EST_DynamicNone) return ESI2;
6354 if (EST2 == EST_DynamicNone) return ESI1;
6355 if (EST1 == EST_BasicNoexcept) return ESI2;
6356 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006357 if (EST1 == EST_NoexceptTrue) return ESI2;
6358 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006359
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006360 // If we're left with value-dependent computed noexcept expressions, we're
6361 // stuck. Before C++17, we can just drop the exception specification entirely,
6362 // since it's not actually part of the canonical type. And this should never
6363 // happen in C++17, because it would mean we were computing the composite
6364 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00006365 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006366 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006367 "computing composite pointer type of dependent types");
6368 return FunctionProtoType::ExceptionSpecInfo();
6369 }
6370
6371 // Switch over the possibilities so that people adding new values know to
6372 // update this function.
6373 switch (EST1) {
6374 case EST_None:
6375 case EST_DynamicNone:
6376 case EST_MSAny:
6377 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00006378 case EST_DependentNoexcept:
6379 case EST_NoexceptFalse:
6380 case EST_NoexceptTrue:
Erich Keaned02f4a12019-05-30 17:31:54 +00006381 case EST_NoThrow:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006382 llvm_unreachable("handled above");
6383
6384 case EST_Dynamic: {
6385 // This is the fun case: both exception specifications are dynamic. Form
6386 // the union of the two lists.
6387 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6388 llvm::SmallPtrSet<QualType, 8> Found;
6389 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6390 for (QualType E : Exceptions)
6391 if (Found.insert(S.Context.getCanonicalType(E)).second)
6392 ExceptionTypeStorage.push_back(E);
6393
6394 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6395 Result.Exceptions = ExceptionTypeStorage;
6396 return Result;
6397 }
6398
6399 case EST_Unevaluated:
6400 case EST_Uninstantiated:
6401 case EST_Unparsed:
6402 llvm_unreachable("shouldn't see unresolved exception specifications here");
6403 }
6404
6405 llvm_unreachable("invalid ExceptionSpecificationType");
6406}
6407
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006408/// Find a merged pointer type and convert the two expressions to it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006409///
Richard Smith9a6f4d42020-01-09 19:24:44 -08006410/// This finds the composite pointer type for \p E1 and \p E2 according to
6411/// C++2a [expr.type]p3. It converts both expressions to this type and returns
6412/// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
6413/// is \c true).
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006414///
Douglas Gregor19175ff2010-04-16 23:20:25 +00006415/// \param Loc The location of the operator requiring these two expressions to
6416/// be converted to the composite pointer type.
6417///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006418/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006419QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00006420 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006421 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006422 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006423
6424 // C++1z [expr]p14:
6425 // The composite pointer type of two operands p1 and p2 having types T1
6426 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006427 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006428
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006429 // where at least one is a pointer or pointer to member type or
6430 // std::nullptr_t is:
6431 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6432 T1->isNullPtrType();
6433 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6434 T2->isNullPtrType();
6435 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00006436 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006437
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006438 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6439 // This can't actually happen, following the standard, but we also use this
6440 // to implement the end of [expr.conv], which hits this case.
6441 //
6442 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6443 if (T1IsPointerLike &&
6444 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006445 if (ConvertArgs)
6446 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6447 ? CK_NullToMemberPointer
6448 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006449 return T1;
6450 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006451 if (T2IsPointerLike &&
6452 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006453 if (ConvertArgs)
6454 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6455 ? CK_NullToMemberPointer
6456 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006457 return T2;
6458 }
Mike Stump11289f42009-09-09 15:08:12 +00006459
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006460 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006461 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006462 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006463 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6464 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006465
Richard Smith9a6f4d42020-01-09 19:24:44 -08006466 struct Step {
6467 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6468 // Qualifiers to apply under the step kind.
6469 Qualifiers Quals;
6470 /// The class for a pointer-to-member; a constant array type with a bound
6471 /// (if any) for an array.
6472 const Type *ClassOrBound;
6473
6474 Step(Kind K, const Type *ClassOrBound = nullptr)
6475 : K(K), Quals(), ClassOrBound(ClassOrBound) {}
6476 QualType rebuild(ASTContext &Ctx, QualType T) const {
6477 T = Ctx.getQualifiedType(T, Quals);
6478 switch (K) {
6479 case Pointer:
6480 return Ctx.getPointerType(T);
6481 case MemberPointer:
6482 return Ctx.getMemberPointerType(T, ClassOrBound);
6483 case ObjCPointer:
6484 return Ctx.getObjCObjectPointerType(T);
6485 case Array:
6486 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6487 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6488 ArrayType::Normal, 0);
6489 else
6490 return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0);
6491 }
6492 llvm_unreachable("unknown step kind");
6493 }
6494 };
6495
6496 SmallVector<Step, 8> Steps;
6497
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006498 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6499 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6500 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6501 // respectively;
6502 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
Richard Smith9a6f4d42020-01-09 19:24:44 -08006503 // to member of C2 of type cv2 U2" for some non-function type U, where
6504 // C1 is reference-related to C2 or C2 is reference-related to C1, the
6505 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6506 // respectively;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006507 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6508 // T2;
6509 //
Richard Smith9a6f4d42020-01-09 19:24:44 -08006510 // Dismantle T1 and T2 to simultaneously determine whether they are similar
6511 // and to prepare to form the cv-combined type if so.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006512 QualType Composite1 = T1;
6513 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006514 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006515 while (true) {
Richard Smith9a6f4d42020-01-09 19:24:44 -08006516 assert(!Composite1.isNull() && !Composite2.isNull());
6517
6518 Qualifiers Q1, Q2;
6519 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
6520 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
6521
6522 // Top-level qualifiers are ignored. Merge at all lower levels.
6523 if (!Steps.empty()) {
6524 // Find the qualifier union: (approximately) the unique minimal set of
6525 // qualifiers that is compatible with both types.
6526 Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |
6527 Q2.getCVRUQualifiers());
6528
6529 // Under one level of pointer or pointer-to-member, we can change to an
6530 // unambiguous compatible address space.
6531 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6532 Quals.setAddressSpace(Q1.getAddressSpace());
6533 } else if (Steps.size() == 1) {
6534 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
6535 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
6536 if (MaybeQ1 == MaybeQ2)
6537 return QualType(); // No unique best address space.
6538 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6539 : Q2.getAddressSpace());
6540 } else {
6541 return QualType();
6542 }
6543
6544 // FIXME: In C, we merge __strong and none to __strong at the top level.
6545 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6546 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6547 else
6548 return QualType();
6549
6550 // Mismatched lifetime qualifiers never compatibly include each other.
6551 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6552 Quals.setObjCLifetime(Q1.getObjCLifetime());
6553 else
6554 return QualType();
6555
6556 Steps.back().Quals = Quals;
6557 if (Q1 != Quals || Q2 != Quals)
6558 NeedConstBefore = Steps.size() - 1;
6559 }
6560
6561 // FIXME: Can we unify the following with UnwrapSimilarTypes?
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006562 const PointerType *Ptr1, *Ptr2;
6563 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6564 (Ptr2 = Composite2->getAs<PointerType>())) {
6565 Composite1 = Ptr1->getPointeeType();
6566 Composite2 = Ptr2->getPointeeType();
Richard Smith9a6f4d42020-01-09 19:24:44 -08006567 Steps.emplace_back(Step::Pointer);
6568 continue;
6569 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006570
Richard Smith9a6f4d42020-01-09 19:24:44 -08006571 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6572 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6573 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6574 Composite1 = ObjPtr1->getPointeeType();
6575 Composite2 = ObjPtr2->getPointeeType();
6576 Steps.emplace_back(Step::ObjCPointer);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006577 continue;
6578 }
Mike Stump11289f42009-09-09 15:08:12 +00006579
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006580 const MemberPointerType *MemPtr1, *MemPtr2;
6581 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6582 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6583 Composite1 = MemPtr1->getPointeeType();
6584 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006585
Richard Smith9a6f4d42020-01-09 19:24:44 -08006586 // At the top level, we can perform a base-to-derived pointer-to-member
6587 // conversion:
6588 //
6589 // - [...] where C1 is reference-related to C2 or C2 is
6590 // reference-related to C1
6591 //
6592 // (Note that the only kinds of reference-relatedness in scope here are
6593 // "same type or derived from".) At any other level, the class must
6594 // exactly match.
6595 const Type *Class = nullptr;
6596 QualType Cls1(MemPtr1->getClass(), 0);
6597 QualType Cls2(MemPtr2->getClass(), 0);
6598 if (Context.hasSameType(Cls1, Cls2))
6599 Class = MemPtr1->getClass();
6600 else if (Steps.empty())
6601 Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
6602 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
6603 if (!Class)
6604 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006605
Richard Smith9a6f4d42020-01-09 19:24:44 -08006606 Steps.emplace_back(Step::MemberPointer, Class);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006607 continue;
6608 }
Mike Stump11289f42009-09-09 15:08:12 +00006609
Richard Smith9a6f4d42020-01-09 19:24:44 -08006610 // Special case: at the top level, we can decompose an Objective-C pointer
6611 // and a 'cv void *'. Unify the qualifiers.
6612 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
6613 Composite2->isObjCObjectPointerType()) ||
6614 (Composite1->isObjCObjectPointerType() &&
6615 Composite2->isVoidPointerType()))) {
6616 Composite1 = Composite1->getPointeeType();
6617 Composite2 = Composite2->getPointeeType();
6618 Steps.emplace_back(Step::Pointer);
6619 continue;
6620 }
6621
6622 // FIXME: arrays
6623
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006624 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006625
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006626 // Cannot unwrap any more types.
6627 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006628 }
Mike Stump11289f42009-09-09 15:08:12 +00006629
Richard Smith9a6f4d42020-01-09 19:24:44 -08006630 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6631 // "pointer to function", where the function types are otherwise the same,
6632 // "pointer to function";
6633 // - if T1 or T2 is "pointer to member of C1 of type function", the other
6634 // type is "pointer to member of C2 of type noexcept function", and C1
6635 // is reference-related to C2 or C2 is reference-related to C1, where
6636 // the function types are otherwise the same, "pointer to member of C2 of
6637 // type function" or "pointer to member of C1 of type function",
6638 // respectively;
6639 //
6640 // We also support 'noreturn' here, so as a Clang extension we generalize the
6641 // above to:
6642 //
6643 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6644 // "pointer to member function" and the pointee types can be unified
6645 // by a function pointer conversion, that conversion is applied
6646 // before checking the following rules.
6647 //
6648 // We've already unwrapped down to the function types, and we want to merge
6649 // rather than just convert, so do this ourselves rather than calling
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006650 // IsFunctionConversion.
6651 //
6652 // FIXME: In order to match the standard wording as closely as possible, we
6653 // currently only do this under a single level of pointers. Ideally, we would
6654 // allow this in general, and set NeedConstBefore to the relevant depth on
Richard Smith9a6f4d42020-01-09 19:24:44 -08006655 // the side(s) where we changed anything. If we permit that, we should also
6656 // consider this conversion when determining type similarity and model it as
6657 // a qualification conversion.
6658 if (Steps.size() == 1) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006659 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6660 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6661 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6662 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6663
6664 // The result is noreturn if both operands are.
6665 bool Noreturn =
6666 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6667 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6668 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6669
6670 // The result is nothrow if both operands are.
6671 SmallVector<QualType, 8> ExceptionTypeStorage;
6672 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6673 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6674 ExceptionTypeStorage);
6675
6676 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6677 FPT1->getParamTypes(), EPI1);
6678 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6679 FPT2->getParamTypes(), EPI2);
6680 }
6681 }
6682 }
6683
Richard Smith9a6f4d42020-01-09 19:24:44 -08006684 // There are some more conversions we can perform under exactly one pointer.
6685 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
6686 !Context.hasSameType(Composite1, Composite2)) {
6687 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6688 // "pointer to cv2 T", where T is an object type or void,
6689 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
6690 if (Composite1->isVoidType() && Composite2->isObjectType())
6691 Composite2 = Composite1;
6692 else if (Composite2->isVoidType() && Composite1->isObjectType())
6693 Composite1 = Composite2;
6694 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6695 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6696 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
6697 // T1, respectively;
6698 //
6699 // The "similar type" handling covers all of this except for the "T1 is a
6700 // base class of T2" case in the definition of reference-related.
6701 else if (IsDerivedFrom(Loc, Composite1, Composite2))
6702 Composite1 = Composite2;
6703 else if (IsDerivedFrom(Loc, Composite2, Composite1))
6704 Composite2 = Composite1;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006705 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006706
Richard Smith9a6f4d42020-01-09 19:24:44 -08006707 // At this point, either the inner types are the same or we have failed to
6708 // find a composite pointer type.
6709 if (!Context.hasSameType(Composite1, Composite2))
6710 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006711
Richard Smith9a6f4d42020-01-09 19:24:44 -08006712 // Per C++ [conv.qual]p3, add 'const' to every level before the last
6713 // differing qualifier.
6714 for (unsigned I = 0; I != NeedConstBefore; ++I)
6715 Steps[I].Quals.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00006716
Richard Smith9a6f4d42020-01-09 19:24:44 -08006717 // Rebuild the composite type.
6718 QualType Composite = Composite1;
6719 for (auto &S : llvm::reverse(Steps))
6720 Composite = S.rebuild(Context, Composite);
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006721
Richard Smith9a6f4d42020-01-09 19:24:44 -08006722 if (ConvertArgs) {
6723 // Convert the expressions to the composite pointer type.
6724 InitializedEntity Entity =
6725 InitializedEntity::InitializeTemporary(Composite);
6726 InitializationKind Kind =
6727 InitializationKind::CreateCopy(Loc, SourceLocation());
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006728
Richard Smith9a6f4d42020-01-09 19:24:44 -08006729 InitializationSequence E1ToC(*this, Entity, Kind, E1);
6730 if (!E1ToC)
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006731 return QualType();
Douglas Gregor19175ff2010-04-16 23:20:25 +00006732
Richard Smith9a6f4d42020-01-09 19:24:44 -08006733 InitializationSequence E2ToC(*this, Entity, Kind, E2);
6734 if (!E2ToC)
6735 return QualType();
6736
6737 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
6738 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
6739 if (E1Result.isInvalid())
6740 return QualType();
6741 E1 = E1Result.get();
6742
6743 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
6744 if (E2Result.isInvalid())
6745 return QualType();
6746 E2 = E2Result.get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006747 }
6748
Richard Smith9a6f4d42020-01-09 19:24:44 -08006749 return Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006750}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006751
John McCalldadc5752010-08-24 06:29:42 +00006752ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006753 if (!E)
6754 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006755
John McCall31168b02011-06-15 23:02:42 +00006756 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6757
6758 // If the result is a glvalue, we shouldn't bind it.
6759 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006760 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006761
John McCall31168b02011-06-15 23:02:42 +00006762 // In ARC, calls that return a retainable type can return retained,
6763 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006764 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006765 E->getType()->isObjCRetainableType()) {
6766
6767 bool ReturnsRetained;
6768
6769 // For actual calls, we compute this by examining the type of the
6770 // called value.
6771 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6772 Expr *Callee = Call->getCallee()->IgnoreParens();
6773 QualType T = Callee->getType();
6774
6775 if (T == Context.BoundMemberTy) {
6776 // Handle pointer-to-members.
6777 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6778 T = BinOp->getRHS()->getType();
6779 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6780 T = Mem->getMemberDecl()->getType();
6781 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006782
John McCall31168b02011-06-15 23:02:42 +00006783 if (const PointerType *Ptr = T->getAs<PointerType>())
6784 T = Ptr->getPointeeType();
6785 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6786 T = Ptr->getPointeeType();
6787 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6788 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006789
Simon Pilgrim94885432020-03-04 11:25:34 +00006790 auto *FTy = T->castAs<FunctionType>();
John McCall31168b02011-06-15 23:02:42 +00006791 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6792
6793 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6794 // type always produce a +1 object.
6795 } else if (isa<StmtExpr>(E)) {
6796 ReturnsRetained = true;
6797
Ted Kremeneke65b0862012-03-06 20:05:56 +00006798 // We hit this case with the lambda conversion-to-block optimization;
6799 // we don't want any extra casts here.
6800 } else if (isa<CastExpr>(E) &&
6801 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006802 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006803
John McCall31168b02011-06-15 23:02:42 +00006804 // For message sends and property references, we try to find an
6805 // actual method. FIXME: we should infer retention by selector in
6806 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006807 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006808 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006809 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6810 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006811 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6812 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006813 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006814 // Don't do reclaims if we're using the zero-element array
6815 // constant.
6816 if (ArrayLit->getNumElements() == 0 &&
6817 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6818 return E;
6819
Ted Kremeneke65b0862012-03-06 20:05:56 +00006820 D = ArrayLit->getArrayWithObjectsMethod();
6821 } else if (ObjCDictionaryLiteral *DictLit
6822 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006823 // Don't do reclaims if we're using the zero-element dictionary
6824 // constant.
6825 if (DictLit->getNumElements() == 0 &&
6826 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6827 return E;
6828
Ted Kremeneke65b0862012-03-06 20:05:56 +00006829 D = DictLit->getDictWithObjectsMethod();
6830 }
John McCall31168b02011-06-15 23:02:42 +00006831
6832 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006833
6834 // Don't do reclaims on performSelector calls; despite their
6835 // return type, the invoked method doesn't necessarily actually
6836 // return an object.
6837 if (!ReturnsRetained &&
6838 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006839 return E;
John McCall31168b02011-06-15 23:02:42 +00006840 }
6841
John McCall16de4d22011-11-14 19:53:16 +00006842 // Don't reclaim an object of Class type.
6843 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006844 return E;
John McCall16de4d22011-11-14 19:53:16 +00006845
Tim Shen4a05bb82016-06-21 20:29:17 +00006846 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006847
John McCall2d637d22011-09-10 06:18:15 +00006848 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6849 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006850 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6851 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006852 }
6853
Akira Hatanakad35a4542019-11-20 18:13:44 -08006854 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
6855 Cleanup.setExprNeedsCleanups(true);
6856
David Blaikiebbafb8a2012-03-11 07:00:24 +00006857 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006858 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006859
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006860 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6861 // a fast path for the common case that the type is directly a RecordType.
6862 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006863 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006864 while (!RT) {
6865 switch (T->getTypeClass()) {
6866 case Type::Record:
6867 RT = cast<RecordType>(T);
6868 break;
6869 case Type::ConstantArray:
6870 case Type::IncompleteArray:
6871 case Type::VariableArray:
6872 case Type::DependentSizedArray:
6873 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6874 break;
6875 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006876 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006877 }
6878 }
Mike Stump11289f42009-09-09 15:08:12 +00006879
Richard Smithfd555f62012-02-22 02:04:18 +00006880 // That should be enough to guarantee that this type is complete, if we're
6881 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006882 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006883 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006884 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006885
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006886 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6887 ExpressionEvaluationContextRecord::EK_Decltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006888 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006889
John McCall31168b02011-06-15 23:02:42 +00006890 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006891 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006892 CheckDestructorAccess(E->getExprLoc(), Destructor,
6893 PDiag(diag::err_access_dtor_temp)
6894 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006895 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6896 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006897
Richard Smithfd555f62012-02-22 02:04:18 +00006898 // If destructor is trivial, we can avoid the extra copy.
6899 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006900 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006901
John McCall28fc7092011-11-10 05:35:25 +00006902 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006903 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006904 }
Richard Smitheec915d62012-02-18 04:13:32 +00006905
6906 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006907 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6908
6909 if (IsDecltype)
6910 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6911
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006912 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006913}
6914
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006915ExprResult
John McCall5d413782010-12-06 08:20:24 +00006916Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006917 if (SubExpr.isInvalid())
6918 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006919
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006920 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006921}
6922
John McCall28fc7092011-11-10 05:35:25 +00006923Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006924 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006925
Eli Friedman3bda6b12012-02-02 23:15:15 +00006926 CleanupVarDeclMarking();
6927
John McCall28fc7092011-11-10 05:35:25 +00006928 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6929 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006930 assert(Cleanup.exprNeedsCleanups() ||
6931 ExprCleanupObjects.size() == FirstCleanup);
6932 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006933 return SubExpr;
6934
Craig Topper5fc8fc22014-08-27 06:28:36 +00006935 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6936 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006937
Tim Shen4a05bb82016-06-21 20:29:17 +00006938 auto *E = ExprWithCleanups::Create(
6939 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006940 DiscardCleanupsInEvaluationContext();
6941
6942 return E;
6943}
6944
John McCall5d413782010-12-06 08:20:24 +00006945Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006946 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006947
Eli Friedman3bda6b12012-02-02 23:15:15 +00006948 CleanupVarDeclMarking();
6949
Tim Shen4a05bb82016-06-21 20:29:17 +00006950 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006951 return SubStmt;
6952
6953 // FIXME: In order to attach the temporaries, wrap the statement into
6954 // a StmtExpr; currently this is only used for asm statements.
6955 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6956 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006957 CompoundStmt *CompStmt = CompoundStmt::Create(
6958 Context, SubStmt, SourceLocation(), SourceLocation());
Richard Smith5c845c12020-03-09 17:34:33 -07006959 Expr *E = new (Context)
6960 StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
6961 /*FIXME TemplateDepth=*/0);
John McCall5d413782010-12-06 08:20:24 +00006962 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006963}
6964
Richard Smithfd555f62012-02-22 02:04:18 +00006965/// Process the expression contained within a decltype. For such expressions,
6966/// certain semantic checks on temporaries are delayed until this point, and
6967/// are omitted for the 'topmost' call in the decltype expression. If the
6968/// topmost call bound a temporary, strip that temporary off the expression.
6969ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006970 assert(ExprEvalContexts.back().ExprContext ==
6971 ExpressionEvaluationContextRecord::EK_Decltype &&
6972 "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006973
Akira Hatanaka0a848562019-01-10 20:12:16 +00006974 ExprResult Result = CheckPlaceholderExpr(E);
6975 if (Result.isInvalid())
6976 return ExprError();
6977 E = Result.get();
6978
Richard Smithfd555f62012-02-22 02:04:18 +00006979 // C++11 [expr.call]p11:
6980 // If a function call is a prvalue of object type,
6981 // -- if the function call is either
6982 // -- the operand of a decltype-specifier, or
6983 // -- the right operand of a comma operator that is the operand of a
6984 // decltype-specifier,
6985 // a temporary object is not introduced for the prvalue.
6986
6987 // Recursively rebuild ParenExprs and comma expressions to strip out the
6988 // outermost CXXBindTemporaryExpr, if any.
6989 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6990 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6991 if (SubExpr.isInvalid())
6992 return ExprError();
6993 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006994 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006995 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006996 }
6997 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6998 if (BO->getOpcode() == BO_Comma) {
6999 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7000 if (RHS.isInvalid())
7001 return ExprError();
7002 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007003 return E;
7004 return new (Context) BinaryOperator(
7005 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00007006 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00007007 }
7008 }
7009
7010 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00007011 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7012 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00007013 if (TopCall)
7014 E = TopCall;
7015 else
Craig Topperc3ec1492014-05-26 06:22:03 +00007016 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00007017
7018 // Disable the special decltype handling now.
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00007019 ExprEvalContexts.back().ExprContext =
7020 ExpressionEvaluationContextRecord::EK_Other;
Richard Smithfd555f62012-02-22 02:04:18 +00007021
Richard Smith4a6861a2019-10-09 02:04:54 +00007022 Result = CheckUnevaluatedOperand(E);
7023 if (Result.isInvalid())
7024 return ExprError();
7025 E = Result.get();
7026
Richard Smithf86b0ae2012-07-28 19:54:11 +00007027 // In MS mode, don't perform any extra checking of call return types within a
7028 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00007029 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007030 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00007031
Richard Smithfd555f62012-02-22 02:04:18 +00007032 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00007033 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7034 I != N; ++I) {
7035 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00007036 if (Call == TopCall)
7037 continue;
7038
David Majnemerced8bdf2015-02-25 17:36:15 +00007039 if (CheckCallReturnType(Call->getCallReturnType(Context),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007040 Call->getBeginLoc(), Call, Call->getDirectCallee()))
Richard Smithfd555f62012-02-22 02:04:18 +00007041 return ExprError();
7042 }
7043
7044 // Now all relevant types are complete, check the destructors are accessible
7045 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00007046 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7047 I != N; ++I) {
7048 CXXBindTemporaryExpr *Bind =
7049 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00007050 if (Bind == TopBind)
7051 continue;
7052
7053 CXXTemporary *Temp = Bind->getTemporary();
7054
7055 CXXRecordDecl *RD =
7056 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7057 CXXDestructorDecl *Destructor = LookupDestructor(RD);
7058 Temp->setDestructor(Destructor);
7059
Richard Smith7d847b12012-05-11 22:20:10 +00007060 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7061 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00007062 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00007063 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00007064 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7065 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00007066
7067 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00007068 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00007069 }
7070
7071 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007072 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00007073}
7074
Richard Smith79c927b2013-11-06 19:31:51 +00007075/// Note a set of 'operator->' functions that were used for a member access.
7076static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00007077 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00007078 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7079 // FIXME: Make this configurable?
7080 unsigned Limit = 9;
7081 if (OperatorArrows.size() > Limit) {
7082 // Produce Limit-1 normal notes and one 'skipping' note.
7083 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7084 SkipCount = OperatorArrows.size() - (Limit - 1);
7085 }
7086
7087 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7088 if (I == SkipStart) {
7089 S.Diag(OperatorArrows[I]->getLocation(),
7090 diag::note_operator_arrows_suppressed)
7091 << SkipCount;
7092 I += SkipCount;
7093 } else {
7094 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7095 << OperatorArrows[I]->getCallResultType();
7096 ++I;
7097 }
7098 }
7099}
7100
Nico Weber964d3322015-02-16 22:35:45 +00007101ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
7102 SourceLocation OpLoc,
7103 tok::TokenKind OpKind,
7104 ParsedType &ObjectType,
7105 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007106 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00007107 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00007108 if (Result.isInvalid()) return ExprError();
7109 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00007110
John McCall526ab472011-10-25 17:37:35 +00007111 Result = CheckPlaceholderExpr(Base);
7112 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007113 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00007114
John McCallb268a282010-08-23 23:25:46 +00007115 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00007116 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007117 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00007118 // If we have a pointer to a dependent type and are using the -> operator,
7119 // the object type is the type that the pointer points to. We might still
7120 // have enough information about that type to do something useful.
7121 if (OpKind == tok::arrow)
7122 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7123 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007124
John McCallba7bf592010-08-24 05:47:05 +00007125 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00007126 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007127 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007128 }
Mike Stump11289f42009-09-09 15:08:12 +00007129
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007130 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00007131 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007132 // returned, with the original second operand.
7133 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00007134 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007135 bool NoArrowOperatorFound = false;
7136 bool FirstIteration = true;
7137 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00007138 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00007139 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00007140 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00007141 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007142
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007143 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00007144 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7145 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00007146 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00007147 noteOperatorArrows(*this, OperatorArrows);
7148 Diag(OpLoc, diag::note_operator_arrow_depth)
7149 << getLangOpts().ArrowDepth;
7150 return ExprError();
7151 }
7152
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007153 Result = BuildOverloadedArrowExpr(
7154 S, Base, OpLoc,
7155 // When in a template specialization and on the first loop iteration,
7156 // potentially give the default diagnostic (with the fixit in a
7157 // separate note) instead of having the error reported back to here
7158 // and giving a diagnostic with a fixit attached to the error itself.
7159 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00007160 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007161 : &NoArrowOperatorFound);
7162 if (Result.isInvalid()) {
7163 if (NoArrowOperatorFound) {
7164 if (FirstIteration) {
7165 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00007166 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007167 << FixItHint::CreateReplacement(OpLoc, ".");
7168 OpKind = tok::period;
7169 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00007170 }
7171 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7172 << BaseType << Base->getSourceRange();
7173 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00007174 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007175 Diag(CD->getBeginLoc(),
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00007176 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007177 }
7178 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007179 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007180 }
John McCallb268a282010-08-23 23:25:46 +00007181 Base = Result.get();
7182 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00007183 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00007184 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00007185 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00007186 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00007187 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7188 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00007189 return ExprError();
7190 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007191 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007192 }
Mike Stump11289f42009-09-09 15:08:12 +00007193
Richard Smith89009442019-05-09 22:22:48 +00007194 if (OpKind == tok::arrow) {
7195 if (BaseType->isPointerType())
7196 BaseType = BaseType->getPointeeType();
7197 else if (auto *AT = Context.getAsArrayType(BaseType))
7198 BaseType = AT->getElementType();
7199 }
Douglas Gregore4f764f2009-11-20 19:58:21 +00007200 }
Mike Stump11289f42009-09-09 15:08:12 +00007201
Douglas Gregorbf3a8262012-01-12 16:11:24 +00007202 // Objective-C properties allow "." access on Objective-C pointer types,
7203 // so adjust the base type to the object type itself.
7204 if (BaseType->isObjCObjectPointerType())
7205 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007206
Douglas Gregorbf3a8262012-01-12 16:11:24 +00007207 // C++ [basic.lookup.classref]p2:
7208 // [...] If the type of the object expression is of pointer to scalar
7209 // type, the unqualified-id is looked up in the context of the complete
7210 // postfix-expression.
7211 //
7212 // This also indicates that we could be parsing a pseudo-destructor-name.
7213 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00007214 // expressions or normal member (ivar or property) access expressions, and
7215 // it's legal for the type to be incomplete if this is a pseudo-destructor
7216 // call. We'll do more incomplete-type checks later in the lookup process,
7217 // so just skip this check for ObjC types.
Richard Smith9e77f522019-08-14 22:57:50 +00007218 if (!BaseType->isRecordType()) {
John McCall9d145df2015-12-14 19:12:54 +00007219 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00007220 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00007221 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00007222 }
Mike Stump11289f42009-09-09 15:08:12 +00007223
Douglas Gregor3024f072012-04-16 07:05:22 +00007224 // The object type must be complete (or dependent), or
7225 // C++11 [expr.prim.general]p3:
7226 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00007227 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00007228 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00007229 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00007230 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007231 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00007232 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007233
Douglas Gregor2b6ca462009-09-03 21:38:09 +00007234 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007235 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00007236 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00007237 // type C (or of pointer to a class type C), the unqualified-id is looked
7238 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00007239 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007240 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007241}
7242
Simon Pilgrim75c26882016-09-30 14:25:09 +00007243static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00007244 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00007245 if (Base->hasPlaceholderType()) {
7246 ExprResult result = S.CheckPlaceholderExpr(Base);
7247 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007248 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00007249 }
7250 ObjectType = Base->getType();
7251
David Blaikie1d578782011-12-16 16:03:09 +00007252 // C++ [expr.pseudo]p2:
7253 // The left-hand side of the dot operator shall be of scalar type. The
7254 // left-hand side of the arrow operator shall be of pointer to scalar type.
7255 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00007256 // Note that this is rather different from the normal handling for the
7257 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00007258 if (OpKind == tok::arrow) {
7259 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7260 ObjectType = Ptr->getPointeeType();
7261 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00007262 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00007263 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7264 << ObjectType << true
7265 << FixItHint::CreateReplacement(OpLoc, ".");
7266 if (S.isSFINAEContext())
7267 return true;
7268
7269 OpKind = tok::period;
7270 }
7271 }
7272
7273 return false;
7274}
7275
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007276/// Check if it's ok to try and recover dot pseudo destructor calls on
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00007277/// pointer objects.
7278static bool
7279canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
7280 QualType DestructedType) {
7281 // If this is a record type, check if its destructor is callable.
7282 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
Bruno Ricci4eb701c2019-01-24 13:52:47 +00007283 if (RD->hasDefinition())
7284 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
7285 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00007286 return false;
7287 }
7288
7289 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7290 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7291 DestructedType->isVectorType();
7292}
7293
John McCalldadc5752010-08-24 06:29:42 +00007294ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00007295 SourceLocation OpLoc,
7296 tok::TokenKind OpKind,
7297 const CXXScopeSpec &SS,
7298 TypeSourceInfo *ScopeTypeInfo,
7299 SourceLocation CCLoc,
7300 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007301 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00007302 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007303
Eli Friedman0ce4de42012-01-25 04:35:06 +00007304 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007305 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7306 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007307
Douglas Gregorc5c57342012-09-10 14:57:06 +00007308 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7309 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00007310 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00007311 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00007312 else {
Nico Weber58829272012-01-23 05:50:57 +00007313 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7314 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00007315 return ExprError();
7316 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007317 }
7318
7319 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007320 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007321 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007322 if (DestructedTypeInfo) {
7323 QualType DestructedType = DestructedTypeInfo->getType();
7324 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00007325 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00007326 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7327 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00007328 // Detect dot pseudo destructor calls on pointer objects, e.g.:
7329 // Foo *foo;
7330 // foo.~Foo();
7331 if (OpKind == tok::period && ObjectType->isPointerType() &&
7332 Context.hasSameUnqualifiedType(DestructedType,
7333 ObjectType->getPointeeType())) {
7334 auto Diagnostic =
7335 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7336 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007337
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00007338 // Issue a fixit only when the destructor is valid.
7339 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
7340 *this, DestructedType))
7341 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
7342
7343 // Recover by setting the object type to the destructed type and the
7344 // operator to '->'.
7345 ObjectType = DestructedType;
7346 OpKind = tok::arrow;
7347 } else {
7348 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7349 << ObjectType << DestructedType << Base->getSourceRange()
7350 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7351
7352 // Recover by setting the destructed type to the object type.
7353 DestructedType = ObjectType;
7354 DestructedTypeInfo =
7355 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7356 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7357 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007358 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00007359 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00007360
John McCall31168b02011-06-15 23:02:42 +00007361 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7362 // Okay: just pretend that the user provided the correctly-qualified
7363 // type.
7364 } else {
7365 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7366 << ObjectType << DestructedType << Base->getSourceRange()
7367 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7368 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007369
John McCall31168b02011-06-15 23:02:42 +00007370 // Recover by setting the destructed type to the object type.
7371 DestructedType = ObjectType;
7372 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7373 DestructedTypeStart);
7374 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7375 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00007376 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007377 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007378
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007379 // C++ [expr.pseudo]p2:
7380 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7381 // form
7382 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007383 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007384 //
7385 // shall designate the same scalar type.
7386 if (ScopeTypeInfo) {
7387 QualType ScopeType = ScopeTypeInfo->getType();
7388 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00007389 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007390
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00007391 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007392 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00007393 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00007394 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007395
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007396 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00007397 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007398 }
7399 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007400
John McCallb268a282010-08-23 23:25:46 +00007401 Expr *Result
7402 = new (Context) CXXPseudoDestructorExpr(Context, Base,
7403 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00007404 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00007405 ScopeTypeInfo,
7406 CCLoc,
7407 TildeLoc,
7408 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007409
David Majnemerced8bdf2015-02-25 17:36:15 +00007410 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007411}
7412
John McCalldadc5752010-08-24 06:29:42 +00007413ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00007414 SourceLocation OpLoc,
7415 tok::TokenKind OpKind,
7416 CXXScopeSpec &SS,
7417 UnqualifiedId &FirstTypeName,
7418 SourceLocation CCLoc,
7419 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007420 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007421 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7422 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007423 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00007424 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7425 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007426 "Invalid second type name in pseudo-destructor");
7427
Eli Friedman0ce4de42012-01-25 04:35:06 +00007428 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007429 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7430 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00007431
7432 // Compute the object type that we should use for name lookup purposes. Only
7433 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00007434 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007435 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00007436 if (ObjectType->isRecordType())
7437 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00007438 else if (ObjectType->isDependentType())
7439 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007441
7442 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007443 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007444 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00007445 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007446 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007447 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007448 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007449 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007450 S, &SS, true, false, ObjectTypePtrForLookup,
7451 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007452 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00007453 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7454 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007455 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00007456 // couldn't find anything useful in scope. Just store the identifier and
7457 // it's location, and we'll perform (qualified) name lookup again at
7458 // template instantiation time.
7459 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7460 SecondTypeName.StartLocation);
7461 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007462 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007463 diag::err_pseudo_dtor_destructor_non_type)
7464 << SecondTypeName.Identifier << ObjectType;
7465 if (isSFINAEContext())
7466 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007467
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007468 // Recover by assuming we had the right type all along.
7469 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007470 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007471 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007472 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007473 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007474 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007475 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007476 TemplateId->NumArgs);
Richard Smithb23c5e82019-05-09 03:31:27 +00007477 TypeResult T = ActOnTemplateIdType(S,
Richard Smitha42fd842020-01-17 15:42:11 -08007478 SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007479 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007480 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007481 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007482 TemplateId->TemplateNameLoc,
7483 TemplateId->LAngleLoc,
7484 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007485 TemplateId->RAngleLoc,
7486 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007487 if (T.isInvalid() || !T.get()) {
7488 // Recover by assuming we had the right type all along.
7489 DestructedType = ObjectType;
7490 } else
7491 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007492 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007493
7494 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007495 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007496 if (!DestructedType.isNull()) {
7497 if (!DestructedTypeInfo)
7498 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007499 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007500 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007502
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007503 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00007504 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007505 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007506 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007507 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007508 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007509 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007510 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007511 S, &SS, true, false, ObjectTypePtrForLookup,
7512 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007513 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007514 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007515 diag::err_pseudo_dtor_destructor_non_type)
7516 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007517
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007518 if (isSFINAEContext())
7519 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007520
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007521 // Just drop this type. It's unnecessary anyway.
7522 ScopeType = QualType();
7523 } else
7524 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007525 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007526 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007527 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007528 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007529 TemplateId->NumArgs);
Richard Smithb23c5e82019-05-09 03:31:27 +00007530 TypeResult T = ActOnTemplateIdType(S,
Richard Smitha42fd842020-01-17 15:42:11 -08007531 SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007532 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007533 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007534 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007535 TemplateId->TemplateNameLoc,
7536 TemplateId->LAngleLoc,
7537 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007538 TemplateId->RAngleLoc,
7539 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007540 if (T.isInvalid() || !T.get()) {
7541 // Recover by dropping this type.
7542 ScopeType = QualType();
7543 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007544 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007545 }
7546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007547
Douglas Gregor90ad9222010-02-24 23:02:30 +00007548 if (!ScopeType.isNull() && !ScopeTypeInfo)
7549 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7550 FirstTypeName.StartLocation);
7551
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007552
John McCallb268a282010-08-23 23:25:46 +00007553 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007554 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007555 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007556}
7557
David Blaikie1d578782011-12-16 16:03:09 +00007558ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7559 SourceLocation OpLoc,
7560 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007561 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007562 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007563 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007564 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7565 return ExprError();
7566
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007567 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7568 false);
David Blaikie1d578782011-12-16 16:03:09 +00007569
7570 TypeLocBuilder TLB;
7571 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7572 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7573 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7574 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7575
7576 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007577 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007578 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007579}
7580
John Wiegley01296292011-04-08 18:41:53 +00007581ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007582 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007583 bool HadMultipleCandidates) {
Richard Smith7ed5fb22018-07-27 17:13:18 +00007584 // Convert the expression to match the conversion function's implicit object
7585 // parameter.
7586 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7587 FoundDecl, Method);
7588 if (Exp.isInvalid())
7589 return true;
7590
Eli Friedman98b01ed2012-03-01 04:01:32 +00007591 if (Method->getParent()->isLambda() &&
7592 Method->getConversionType()->isBlockPointerType()) {
Jan Korouse72321f2019-07-23 16:54:11 +00007593 // This is a lambda conversion to block pointer; check if the argument
Richard Smith7ed5fb22018-07-27 17:13:18 +00007594 // was a LambdaExpr.
Eli Friedman98b01ed2012-03-01 04:01:32 +00007595 Expr *SubE = E;
7596 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7597 if (CE && CE->getCastKind() == CK_NoOp)
7598 SubE = CE->getSubExpr();
7599 SubE = SubE->IgnoreParens();
7600 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7601 SubE = BE->getSubExpr();
7602 if (isa<LambdaExpr>(SubE)) {
7603 // For the conversion to block pointer on a lambda expression, we
7604 // construct a special BlockLiteral instead; this doesn't really make
7605 // a difference in ARC, but outside of ARC the resulting block literal
7606 // follows the normal lifetime rules for block literals instead of being
7607 // autoreleased.
7608 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007609 PushExpressionEvaluationContext(
7610 ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith7ed5fb22018-07-27 17:13:18 +00007611 ExprResult BlockExp = BuildBlockForLambdaConversion(
7612 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
Akira Hatanakac482acd2016-05-04 18:07:20 +00007613 PopExpressionEvaluationContext();
7614
Richard Smith7ed5fb22018-07-27 17:13:18 +00007615 if (BlockExp.isInvalid())
7616 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7617 return BlockExp;
Eli Friedman98b01ed2012-03-01 04:01:32 +00007618 }
7619 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007620
Richard Smith84be9982019-06-06 23:24:18 +00007621 MemberExpr *ME =
7622 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
7623 NestedNameSpecifierLoc(), SourceLocation(), Method,
7624 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
7625 HadMultipleCandidates, DeclarationNameInfo(),
7626 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007627
Alp Toker314cc812014-01-25 16:55:45 +00007628 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007629 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7630 ResultType = ResultType.getNonLValueExprType(Context);
7631
Bruno Riccic5885cf2018-12-21 15:20:32 +00007632 CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
7633 Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc());
George Burgess IVce6284b2017-01-28 02:19:40 +00007634
7635 if (CheckFunctionCall(Method, CE,
7636 Method->getType()->castAs<FunctionProtoType>()))
7637 return ExprError();
7638
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007639 return CE;
7640}
7641
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007642ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7643 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007644 // If the operand is an unresolved lookup expression, the expression is ill-
7645 // formed per [over.over]p1, because overloaded function names cannot be used
7646 // without arguments except in explicit contexts.
7647 ExprResult R = CheckPlaceholderExpr(Operand);
7648 if (R.isInvalid())
7649 return R;
7650
Richard Smith4a6861a2019-10-09 02:04:54 +00007651 R = CheckUnevaluatedOperand(R.get());
7652 if (R.isInvalid())
7653 return ExprError();
7654
Aaron Ballmanedc80842015-04-27 22:31:12 +00007655 Operand = R.get();
7656
Richard Smith51ec0cf2017-02-21 01:17:38 +00007657 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007658 // The expression operand for noexcept is in an unevaluated expression
7659 // context, so side effects could result in unintended consequences.
7660 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7661 }
7662
Richard Smithf623c962012-04-17 00:58:00 +00007663 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007664 return new (Context)
7665 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007666}
7667
7668ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7669 Expr *Operand, SourceLocation RParen) {
7670 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007671}
7672
Eli Friedmanf798f652012-05-24 22:04:19 +00007673static bool IsSpecialDiscardedValue(Expr *E) {
7674 // In C++11, discarded-value expressions of a certain form are special,
7675 // according to [expr]p10:
7676 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7677 // expression is an lvalue of volatile-qualified type and it has
7678 // one of the following forms:
7679 E = E->IgnoreParens();
7680
Eli Friedmanc49c2262012-05-24 22:36:31 +00007681 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007682 if (isa<DeclRefExpr>(E))
7683 return true;
7684
Eli Friedmanc49c2262012-05-24 22:36:31 +00007685 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007686 if (isa<ArraySubscriptExpr>(E))
7687 return true;
7688
Eli Friedmanc49c2262012-05-24 22:36:31 +00007689 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007690 if (isa<MemberExpr>(E))
7691 return true;
7692
Eli Friedmanc49c2262012-05-24 22:36:31 +00007693 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007694 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7695 if (UO->getOpcode() == UO_Deref)
7696 return true;
7697
7698 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007699 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007700 if (BO->isPtrMemOp())
7701 return true;
7702
Eli Friedmanc49c2262012-05-24 22:36:31 +00007703 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007704 if (BO->getOpcode() == BO_Comma)
7705 return IsSpecialDiscardedValue(BO->getRHS());
7706 }
7707
Eli Friedmanc49c2262012-05-24 22:36:31 +00007708 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007709 // operands are one of the above, or
7710 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7711 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7712 IsSpecialDiscardedValue(CO->getFalseExpr());
7713 // The related edge case of "*x ?: *x".
7714 if (BinaryConditionalOperator *BCO =
7715 dyn_cast<BinaryConditionalOperator>(E)) {
7716 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7717 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7718 IsSpecialDiscardedValue(BCO->getFalseExpr());
7719 }
7720
7721 // Objective-C++ extensions to the rule.
7722 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7723 return true;
7724
7725 return false;
7726}
7727
John McCall34376a62010-12-04 03:47:34 +00007728/// Perform the conversions required for an expression used in a
7729/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007730ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007731 if (E->hasPlaceholderType()) {
7732 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007733 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007734 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007735 }
7736
John McCallfee942d2010-12-02 02:07:15 +00007737 // C99 6.3.2.1:
7738 // [Except in specific positions,] an lvalue that does not have
7739 // array type is converted to the value stored in the
7740 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007741 if (E->isRValue()) {
7742 // In C, function designators (i.e. expressions of function type)
7743 // are r-values, but we still want to do function-to-pointer decay
7744 // on them. This is both technically correct and convenient for
7745 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007746 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007747 return DefaultFunctionArrayConversion(E);
7748
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007749 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007750 }
John McCallfee942d2010-12-02 02:07:15 +00007751
Eli Friedmanf798f652012-05-24 22:04:19 +00007752 if (getLangOpts().CPlusPlus) {
7753 // The C++11 standard defines the notion of a discarded-value expression;
7754 // normally, we don't need to do anything to handle it, but if it is a
7755 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7756 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007757 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Richard Smith4a6861a2019-10-09 02:04:54 +00007758 E->getType().isVolatileQualified()) {
7759 if (IsSpecialDiscardedValue(E)) {
7760 ExprResult Res = DefaultLvalueConversion(E);
7761 if (Res.isInvalid())
7762 return E;
7763 E = Res.get();
7764 } else {
7765 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7766 // it occurs as a discarded-value expression.
7767 CheckUnusedVolatileAssignment(E);
7768 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007769 }
Richard Smith122f88d2016-12-06 23:52:28 +00007770
7771 // C++1z:
7772 // If the expression is a prvalue after this optional conversion, the
7773 // temporary materialization conversion is applied.
7774 //
7775 // We skip this step: IR generation is able to synthesize the storage for
7776 // itself in the aggregate case, and adding the extra node to the AST is
7777 // just clutter.
7778 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7779 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007780 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007781 }
John McCall34376a62010-12-04 03:47:34 +00007782
7783 // GCC seems to also exclude expressions of incomplete enum type.
7784 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7785 if (!T->getDecl()->isComplete()) {
7786 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007787 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007788 return E;
John McCall34376a62010-12-04 03:47:34 +00007789 }
7790 }
7791
John Wiegley01296292011-04-08 18:41:53 +00007792 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7793 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007794 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007795 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007796
John McCallca61b652010-12-04 12:29:11 +00007797 if (!E->getType()->isVoidType())
7798 RequireCompleteType(E->getExprLoc(), E->getType(),
7799 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007800 return E;
John McCall34376a62010-12-04 03:47:34 +00007801}
7802
Richard Smith4a6861a2019-10-09 02:04:54 +00007803ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {
7804 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7805 // it occurs as an unevaluated operand.
7806 CheckUnusedVolatileAssignment(E);
7807
7808 return E;
7809}
7810
Faisal Valia17d19f2013-11-07 05:17:06 +00007811// If we can unambiguously determine whether Var can never be used
7812// in a constant expression, return true.
7813// - if the variable and its initializer are non-dependent, then
7814// we can unambiguously check if the variable is a constant expression.
7815// - if the initializer is not value dependent - we can determine whether
7816// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007817// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007818// never be a constant expression.
7819// - FXIME: if the initializer is dependent, we can still do some analysis and
7820// identify certain cases unambiguously as non-const by using a Visitor:
7821// - such as those that involve odr-use of a ParmVarDecl, involve a new
7822// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007823static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007824 ASTContext &Context) {
7825 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007826 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007827
7828 // If there is no initializer - this can not be a constant expression.
7829 if (!Var->getAnyInitializer(DefVD)) return true;
7830 assert(DefVD);
7831 if (DefVD->isWeak()) return false;
7832 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007833
Faisal Valia17d19f2013-11-07 05:17:06 +00007834 Expr *Init = cast<Expr>(Eval->Value);
7835
7836 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007837 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7838 // of value-dependent expressions, and use it here to determine whether the
7839 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007840 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007841 }
7842
Richard Smith715f7a12019-06-11 17:50:32 +00007843 return !Var->isUsableInConstantExpressions(Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007844}
7845
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007846/// Check if the current lambda has any potential captures
Simon Pilgrim75c26882016-09-30 14:25:09 +00007847/// that must be captured by any of its enclosing lambdas that are ready to
7848/// capture. If there is a lambda that can capture a nested
7849/// potential-capture, go ahead and do so. Also, check to see if any
7850/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007851/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007852
Faisal Valiab3d6462013-12-07 20:22:44 +00007853static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7854 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7855
Simon Pilgrim75c26882016-09-30 14:25:09 +00007856 assert(!S.isUnevaluatedContext());
7857 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007858#ifndef NDEBUG
7859 DeclContext *DC = S.CurContext;
7860 while (DC && isa<CapturedDecl>(DC))
7861 DC = DC->getParent();
7862 assert(
7863 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007864 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007865#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007866
7867 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7868
Faisal Valiab3d6462013-12-07 20:22:44 +00007869 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007870 // lambda (within a generic outer lambda), must be captured by an
7871 // outer lambda that is enclosed within a non-dependent context.
Richard Smith7bf8f6f2019-06-04 17:17:20 +00007872 CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007873 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007874 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007875 // need to check enclosing lambda's for speculative captures.
7876 // For e.g.:
7877 // Even though 'x' is not odr-used, it should be captured.
7878 // int test() {
7879 // const int x = 10;
7880 // auto L = [=](auto a) {
7881 // (void) +x + a;
7882 // };
7883 // }
7884 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007885 !IsFullExprInstantiationDependent)
Richard Smith7bf8f6f2019-06-04 17:17:20 +00007886 return;
Faisal Valiab3d6462013-12-07 20:22:44 +00007887
7888 // If we have a capture-capable lambda for the variable, go ahead and
7889 // capture the variable in that lambda (and all its enclosing lambdas).
7890 if (const Optional<unsigned> Index =
7891 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Richard Smith94ef6862019-05-28 23:09:42 +00007892 S.FunctionScopes, Var, S))
7893 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(),
7894 Index.getValue());
Simon Pilgrim75c26882016-09-30 14:25:09 +00007895 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007896 VariableCanNeverBeAConstantExpression(Var, S.Context);
7897 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7898 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007899 // can not be used in a constant expression - which means
7900 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007901 // capture violation early, if the variable is un-captureable.
7902 // This is purely for diagnosing errors early. Otherwise, this
7903 // error would get diagnosed when the lambda becomes capture ready.
7904 QualType CaptureType, DeclRefType;
7905 SourceLocation ExprLoc = VarExpr->getExprLoc();
7906 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007907 /*EllipsisLoc*/ SourceLocation(),
7908 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007909 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007910 // We will never be able to capture this variable, and we need
7911 // to be able to in any and all instantiations, so diagnose it.
7912 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007913 /*EllipsisLoc*/ SourceLocation(),
7914 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007915 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007916 }
7917 }
Richard Smith7bf8f6f2019-06-04 17:17:20 +00007918 });
Faisal Valia17d19f2013-11-07 05:17:06 +00007919
Faisal Valiab3d6462013-12-07 20:22:44 +00007920 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007921 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007922 // If we have a capture-capable lambda for 'this', go ahead and capture
7923 // 'this' in that lambda (and all its enclosing lambdas).
7924 if (const Optional<unsigned> Index =
7925 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007926 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007927 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7928 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7929 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7930 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007931 }
7932 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007933
7934 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007935 CurrentLSI->clearPotentialCaptures();
7936}
7937
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007938static ExprResult attemptRecovery(Sema &SemaRef,
7939 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007940 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007941 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7942 Consumer.getLookupResult().getLookupKind());
7943 const CXXScopeSpec *SS = Consumer.getSS();
7944 CXXScopeSpec NewSS;
7945
7946 // Use an approprate CXXScopeSpec for building the expr.
7947 if (auto *NNS = TC.getCorrectionSpecifier())
7948 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7949 else if (SS && !TC.WillReplaceSpecifier())
7950 NewSS = *SS;
7951
Richard Smithde6d6c42015-12-29 19:43:10 +00007952 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007953 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007954 R.addDecl(ND);
7955 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007956 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007957 CXXRecordDecl *Record = nullptr;
7958 if (auto *NNS = TC.getCorrectionSpecifier())
7959 Record = NNS->getAsType()->getAsCXXRecordDecl();
7960 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007961 Record =
7962 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7963 if (Record)
7964 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007965
7966 // Detect and handle the case where the decl might be an implicit
7967 // member.
7968 bool MightBeImplicitMember;
7969 if (!Consumer.isAddressOfOperand())
7970 MightBeImplicitMember = true;
7971 else if (!NewSS.isEmpty())
7972 MightBeImplicitMember = false;
7973 else if (R.isOverloadedResult())
7974 MightBeImplicitMember = false;
7975 else if (R.isUnresolvableResult())
7976 MightBeImplicitMember = true;
7977 else
7978 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7979 isa<IndirectFieldDecl>(ND) ||
7980 isa<MSPropertyDecl>(ND);
7981
7982 if (MightBeImplicitMember)
7983 return SemaRef.BuildPossibleImplicitMemberExpr(
7984 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007985 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007986 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7987 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7988 Ivar->getIdentifier());
7989 }
7990 }
7991
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007992 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7993 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007994}
7995
Kaelyn Takata6c759512014-10-27 18:07:37 +00007996namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007997class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7998 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7999
8000public:
8001 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8002 : TypoExprs(TypoExprs) {}
8003 bool VisitTypoExpr(TypoExpr *TE) {
8004 TypoExprs.insert(TE);
8005 return true;
8006 }
8007};
8008
Kaelyn Takata6c759512014-10-27 18:07:37 +00008009class TransformTypos : public TreeTransform<TransformTypos> {
8010 typedef TreeTransform<TransformTypos> BaseTransform;
8011
Kaelyn Takatab8499f02015-05-05 19:17:03 +00008012 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8013 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00008014 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00008015 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00008016 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008017 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00008018
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008019 /// Emit diagnostics for all of the TypoExprs encountered.
David Goldmanfd4d7772019-08-20 19:03:15 +00008020 ///
Kaelyn Takata6c759512014-10-27 18:07:37 +00008021 /// If the TypoExprs were successfully corrected, then the diagnostics should
8022 /// suggest the corrections. Otherwise the diagnostics will not suggest
8023 /// anything (having been passed an empty TypoCorrection).
David Goldmanfd4d7772019-08-20 19:03:15 +00008024 ///
8025 /// If we've failed to correct due to ambiguous corrections, we need to
8026 /// be sure to pass empty corrections and replacements. Otherwise it's
8027 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8028 /// and we don't want to report those diagnostics.
8029 void EmitAllDiagnostics(bool IsAmbiguous) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00008030 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00008031 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008032 if (State.DiagHandler) {
David Goldmanfd4d7772019-08-20 19:03:15 +00008033 TypoCorrection TC = IsAmbiguous
8034 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
8035 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008036
8037 // Extract the NamedDecl from the transformed TypoExpr and add it to the
8038 // TypoCorrection, replacing the existing decls. This ensures the right
8039 // NamedDecl is used in diagnostics e.g. in the case where overload
8040 // resolution was used to select one from several possible decls that
8041 // had been stored in the TypoCorrection.
8042 if (auto *ND = getDeclFromExpr(
8043 Replacement.isInvalid() ? nullptr : Replacement.get()))
8044 TC.setCorrectionDecl(ND);
8045
8046 State.DiagHandler(TC);
8047 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00008048 SemaRef.clearDelayedTypo(TE);
8049 }
8050 }
8051
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008052 /// If corrections for the first TypoExpr have been exhausted for a
Kaelyn Takata6c759512014-10-27 18:07:37 +00008053 /// given combination of the other TypoExprs, retry those corrections against
8054 /// the next combination of substitutions for the other TypoExprs by advancing
8055 /// to the next potential correction of the second TypoExpr. For the second
8056 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
8057 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
8058 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
8059 /// TransformCache). Returns true if there is still any untried combinations
8060 /// of corrections.
8061 bool CheckAndAdvanceTypoExprCorrectionStreams() {
8062 for (auto TE : TypoExprs) {
8063 auto &State = SemaRef.getTypoExprState(TE);
8064 TransformCache.erase(TE);
8065 if (!State.Consumer->finished())
8066 return true;
8067 State.Consumer->resetCorrectionStream();
8068 }
8069 return false;
8070 }
8071
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008072 NamedDecl *getDeclFromExpr(Expr *E) {
8073 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8074 E = OverloadResolution[OE];
8075
8076 if (!E)
8077 return nullptr;
8078 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00008079 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008080 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00008081 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008082 // FIXME: Add any other expr types that could be be seen by the delayed typo
8083 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00008084 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008085 return nullptr;
8086 }
8087
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00008088 ExprResult TryTransform(Expr *E) {
8089 Sema::SFINAETrap Trap(SemaRef);
8090 ExprResult Res = TransformExpr(E);
8091 if (Trap.hasErrorOccurred() || Res.isInvalid())
8092 return ExprError();
8093
8094 return ExprFilter(Res.get());
8095 }
8096
David Goldmanfd4d7772019-08-20 19:03:15 +00008097 // Since correcting typos may intoduce new TypoExprs, this function
8098 // checks for new TypoExprs and recurses if it finds any. Note that it will
8099 // only succeed if it is able to correct all typos in the given expression.
8100 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8101 if (Res.isInvalid()) {
8102 return Res;
8103 }
8104 // Check to see if any new TypoExprs were created. If so, we need to recurse
8105 // to check their validity.
8106 Expr *FixedExpr = Res.get();
8107
8108 auto SavedTypoExprs = std::move(TypoExprs);
8109 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8110 TypoExprs.clear();
8111 AmbiguousTypoExprs.clear();
8112
8113 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8114 if (!TypoExprs.empty()) {
8115 // Recurse to handle newly created TypoExprs. If we're not able to
8116 // handle them, discard these TypoExprs.
8117 ExprResult RecurResult =
8118 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8119 if (RecurResult.isInvalid()) {
8120 Res = ExprError();
8121 // Recursive corrections didn't work, wipe them away and don't add
8122 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8123 // since we don't want to clear them twice. Note: it's possible the
8124 // TypoExprs were created recursively and thus won't be in our
8125 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8126 auto &SemaTypoExprs = SemaRef.TypoExprs;
8127 for (auto TE : TypoExprs) {
8128 TransformCache.erase(TE);
8129 SemaRef.clearDelayedTypo(TE);
8130
8131 auto SI = find(SemaTypoExprs, TE);
8132 if (SI != SemaTypoExprs.end()) {
8133 SemaTypoExprs.erase(SI);
8134 }
8135 }
8136 } else {
8137 // TypoExpr is valid: add newly created TypoExprs since we were
8138 // able to correct them.
8139 Res = RecurResult;
8140 SavedTypoExprs.set_union(TypoExprs);
8141 }
8142 }
8143
8144 TypoExprs = std::move(SavedTypoExprs);
8145 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8146
8147 return Res;
8148 }
8149
8150 // Try to transform the given expression, looping through the correction
8151 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8152 //
8153 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8154 // true and this method immediately will return an `ExprError`.
8155 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8156 ExprResult Res;
8157 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8158 SemaRef.TypoExprs.clear();
8159
8160 while (true) {
8161 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8162
8163 // Recursion encountered an ambiguous correction. This means that our
8164 // correction itself is ambiguous, so stop now.
8165 if (IsAmbiguous)
8166 break;
8167
8168 // If the transform is still valid after checking for any new typos,
8169 // it's good to go.
8170 if (!Res.isInvalid())
8171 break;
8172
8173 // The transform was invalid, see if we have any TypoExprs with untried
8174 // correction candidates.
8175 if (!CheckAndAdvanceTypoExprCorrectionStreams())
8176 break;
8177 }
8178
8179 // If we found a valid result, double check to make sure it's not ambiguous.
8180 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
David Goldman7a2b7042019-10-25 13:15:25 -04008181 auto SavedTransformCache =
8182 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8183
David Goldmanfd4d7772019-08-20 19:03:15 +00008184 // Ensure none of the TypoExprs have multiple typo correction candidates
8185 // with the same edit length that pass all the checks and filters.
8186 while (!AmbiguousTypoExprs.empty()) {
8187 auto TE = AmbiguousTypoExprs.back();
8188
8189 // TryTransform itself can create new Typos, adding them to the TypoExpr map
8190 // and invalidating our TypoExprState, so always fetch it instead of storing.
8191 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8192
8193 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8194 TypoCorrection Next;
8195 do {
David Goldman6d186502019-09-13 14:43:24 +00008196 // Fetch the next correction by erasing the typo from the cache and calling
8197 // `TryTransform` which will iterate through corrections in
8198 // `TransformTypoExpr`.
8199 TransformCache.erase(TE);
David Goldmanfd4d7772019-08-20 19:03:15 +00008200 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8201
8202 if (!AmbigRes.isInvalid() || IsAmbiguous) {
8203 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8204 SavedTransformCache.erase(TE);
8205 Res = ExprError();
8206 IsAmbiguous = true;
8207 break;
8208 }
8209 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8210 Next.getEditDistance(false) == TC.getEditDistance(false));
8211
8212 if (IsAmbiguous)
8213 break;
8214
8215 AmbiguousTypoExprs.remove(TE);
8216 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8217 }
8218 TransformCache = std::move(SavedTransformCache);
8219 }
8220
8221 // Wipe away any newly created TypoExprs that we don't know about. Since we
8222 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8223 // possible if a `TypoExpr` is created during a transformation but then
8224 // fails before we can discover it.
8225 auto &SemaTypoExprs = SemaRef.TypoExprs;
8226 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8227 auto TE = *Iterator;
8228 auto FI = find(TypoExprs, TE);
8229 if (FI != TypoExprs.end()) {
8230 Iterator++;
8231 continue;
8232 }
8233 SemaRef.clearDelayedTypo(TE);
8234 Iterator = SemaTypoExprs.erase(Iterator);
8235 }
8236 SemaRef.TypoExprs = std::move(SavedTypoExprs);
8237
8238 return Res;
8239 }
8240
Kaelyn Takata6c759512014-10-27 18:07:37 +00008241public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00008242 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8243 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00008244
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008245 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8246 MultiExprArg Args,
8247 SourceLocation RParenLoc,
8248 Expr *ExecConfig = nullptr) {
8249 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8250 RParenLoc, ExecConfig);
8251 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00008252 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00008253 Expr *ResultCall = Result.get();
8254 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8255 ResultCall = BE->getSubExpr();
8256 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8257 OverloadResolution[OE] = CE->getCallee();
8258 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008259 }
8260 return Result;
8261 }
8262
Kaelyn Takata6c759512014-10-27 18:07:37 +00008263 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8264
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00008265 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8266
Kaelyn Takata6c759512014-10-27 18:07:37 +00008267 ExprResult Transform(Expr *E) {
David Goldmanfd4d7772019-08-20 19:03:15 +00008268 bool IsAmbiguous = false;
8269 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
Kaelyn Takata49d84322014-11-11 23:26:56 +00008270
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00008271 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00008272 FindTypoExprs(TypoExprs).TraverseStmt(E);
8273
David Goldmanfd4d7772019-08-20 19:03:15 +00008274 EmitAllDiagnostics(IsAmbiguous);
Kaelyn Takata6c759512014-10-27 18:07:37 +00008275
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00008276 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00008277 }
8278
8279 ExprResult TransformTypoExpr(TypoExpr *E) {
8280 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8281 // cached transformation result if there is one and the TypoExpr isn't the
8282 // first one that was encountered.
8283 auto &CacheEntry = TransformCache[E];
8284 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8285 return CacheEntry;
8286 }
8287
8288 auto &State = SemaRef.getTypoExprState(E);
8289 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
8290
8291 // For the first TypoExpr and an uncached TypoExpr, find the next likely
8292 // typo correction and return it.
8293 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00008294 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00008295 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00008296 // FIXME: If we would typo-correct to an invalid declaration, it's
8297 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00008298 ExprResult NE = State.RecoveryHandler ?
8299 State.RecoveryHandler(SemaRef, E, TC) :
8300 attemptRecovery(SemaRef, *State.Consumer, TC);
8301 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00008302 // Check whether there may be a second viable correction with the same
8303 // edit distance; if so, remember this TypoExpr may have an ambiguous
8304 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00008305 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00008306 if ((Next = State.Consumer->peekNextCorrection()) &&
8307 Next.getEditDistance(false) == TC.getEditDistance(false)) {
8308 AmbiguousTypoExprs.insert(E);
8309 } else {
8310 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00008311 }
8312 assert(!NE.isUnset() &&
8313 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00008314 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00008315 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00008316 }
8317 return CacheEntry = ExprError();
8318 }
8319};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008320}
Faisal Valia17d19f2013-11-07 05:17:06 +00008321
Kaelyn Takatab8499f02015-05-05 19:17:03 +00008322ExprResult
8323Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
8324 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00008325 // If the current evaluation context indicates there are uncorrected typos
8326 // and the current expression isn't guaranteed to not have typos, try to
8327 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00008328 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00008329 (E->isTypeDependent() || E->isValueDependent() ||
8330 E->isInstantiationDependent())) {
8331 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00008332 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00008333 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00008334 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00008335 ExprEvalContexts.back().NumTypos -= TyposResolved;
8336 return Result;
8337 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00008338 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00008339 }
8340 return E;
8341}
8342
Richard Smith945f8d32013-01-14 22:39:08 +00008343ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008344 bool DiscardedValue,
Richard Smithb3d203f2018-10-19 19:01:34 +00008345 bool IsConstexpr) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008346 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00008347
8348 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00008349 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00008350
Richard Smithb3d203f2018-10-19 19:01:34 +00008351 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00008352 return ExprError();
8353
Richard Smith945f8d32013-01-14 22:39:08 +00008354 if (DiscardedValue) {
Richard Smithb3d203f2018-10-19 19:01:34 +00008355 // Top-level expressions default to 'id' when we're in a debugger.
8356 if (getLangOpts().DebuggerCastResultToId &&
8357 FullExpr.get()->getType() == Context.UnknownAnyTy) {
8358 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
8359 if (FullExpr.isInvalid())
8360 return ExprError();
8361 }
8362
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008363 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00008364 if (FullExpr.isInvalid())
8365 return ExprError();
8366
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008367 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00008368 if (FullExpr.isInvalid())
8369 return ExprError();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00008370
8371 DiagnoseUnusedExprResult(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00008372 }
John Wiegley01296292011-04-08 18:41:53 +00008373
Kaelyn Takata49d84322014-11-11 23:26:56 +00008374 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
8375 if (FullExpr.isInvalid())
8376 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00008377
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008378 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00008379
Simon Pilgrim75c26882016-09-30 14:25:09 +00008380 // At the end of this full expression (which could be a deeply nested
8381 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00008382 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00008383 // Consider the following code:
8384 // void f(int, int);
8385 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00008386 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00008387 // const int x = 10, y = 20;
8388 // auto L = [=](auto a) {
8389 // auto M = [=](auto b) {
8390 // f(x, b); <-- requires x to be captured by L and M
8391 // f(y, a); <-- requires y to be captured by L, but not all Ms
8392 // };
8393 // };
8394 // }
8395
Simon Pilgrim75c26882016-09-30 14:25:09 +00008396 // FIXME: Also consider what happens for something like this that involves
8397 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00008398 // void f() {
8399 // const int n = 0;
8400 // auto L = [&](auto a) {
8401 // +n + ({ 0; a; });
8402 // };
8403 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00008404 //
8405 // Here, we see +n, and then the full-expression 0; ends, so we don't
8406 // capture n (and instead remove it from our list of potential captures),
8407 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00008408 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00008409
Alexey Bataev31939e32016-11-11 12:36:20 +00008410 LambdaScopeInfo *const CurrentLSI =
8411 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00008412 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00008413 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00008414 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00008415 // By ensuring we are in the context of a lambda's call operator
8416 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00008417 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00008418 // PR, a proper fix would entail :
8419 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00008420 // - Add to Sema an integer holding the smallest (outermost) scope
8421 // index that we are *lexically* within, and save/restore/set to
8422 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00008423 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00008424 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00008425 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00008426 DeclContext *DC = CurContext;
8427 while (DC && isa<CapturedDecl>(DC))
8428 DC = DC->getParent();
8429 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00008430 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00008431 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00008432 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
8433 *this);
John McCall5d413782010-12-06 08:20:24 +00008434 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00008435}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00008436
8437StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
8438 if (!FullStmt) return StmtError();
8439
John McCall5d413782010-12-06 08:20:24 +00008440 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00008441}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008442
Simon Pilgrim75c26882016-09-30 14:25:09 +00008443Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00008444Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
8445 CXXScopeSpec &SS,
8446 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008447 DeclarationName TargetName = TargetNameInfo.getName();
8448 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00008449 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008450
Douglas Gregor43edb322011-10-24 22:31:10 +00008451 // If the name itself is dependent, then the result is dependent.
8452 if (TargetName.isDependentName())
8453 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008454
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008455 // Do the redeclaration lookup in the current scope.
8456 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
8457 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00008458 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008459 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00008460
Douglas Gregor43edb322011-10-24 22:31:10 +00008461 switch (R.getResultKind()) {
8462 case LookupResult::Found:
8463 case LookupResult::FoundOverloaded:
8464 case LookupResult::FoundUnresolvedValue:
8465 case LookupResult::Ambiguous:
8466 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008467
Douglas Gregor43edb322011-10-24 22:31:10 +00008468 case LookupResult::NotFound:
8469 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008470
Douglas Gregor43edb322011-10-24 22:31:10 +00008471 case LookupResult::NotFoundInCurrentInstantiation:
8472 return IER_Dependent;
8473 }
David Blaikie8a40f702012-01-17 06:56:22 +00008474
8475 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008476}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00008477
Simon Pilgrim75c26882016-09-30 14:25:09 +00008478Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00008479Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
8480 bool IsIfExists, CXXScopeSpec &SS,
8481 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00008482 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00008483
Richard Smith151c4562016-12-20 21:35:28 +00008484 // Check for an unexpanded parameter pack.
8485 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
8486 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
8487 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00008488 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008489
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00008490 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
8491}
Saar Raza0f50d72020-01-18 09:11:43 +02008492
8493concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {
8494 return BuildExprRequirement(E, /*IsSimple=*/true,
8495 /*NoexceptLoc=*/SourceLocation(),
8496 /*ReturnTypeRequirement=*/{});
8497}
8498
8499concepts::Requirement *
8500Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS,
8501 SourceLocation NameLoc, IdentifierInfo *TypeName,
8502 TemplateIdAnnotation *TemplateId) {
8503 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
8504 "Exactly one of TypeName and TemplateId must be specified.");
8505 TypeSourceInfo *TSI = nullptr;
8506 if (TypeName) {
8507 QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc,
8508 SS.getWithLocInContext(Context), *TypeName,
8509 NameLoc, &TSI, /*DeducedTypeContext=*/false);
8510 if (T.isNull())
8511 return nullptr;
8512 } else {
8513 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
8514 TemplateId->NumArgs);
8515 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
8516 TemplateId->TemplateKWLoc,
8517 TemplateId->Template, TemplateId->Name,
8518 TemplateId->TemplateNameLoc,
8519 TemplateId->LAngleLoc, ArgsPtr,
8520 TemplateId->RAngleLoc);
8521 if (T.isInvalid())
8522 return nullptr;
8523 if (GetTypeFromParser(T.get(), &TSI).isNull())
8524 return nullptr;
8525 }
8526 return BuildTypeRequirement(TSI);
8527}
8528
8529concepts::Requirement *
8530Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {
8531 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
8532 /*ReturnTypeRequirement=*/{});
8533}
8534
8535concepts::Requirement *
8536Sema::ActOnCompoundRequirement(
8537 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8538 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
8539 // C++2a [expr.prim.req.compound] p1.3.3
8540 // [..] the expression is deduced against an invented function template
8541 // F [...] F is a void function template with a single type template
8542 // parameter T declared with the constrained-parameter. Form a new
8543 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
8544 // around the constrained-parameter. F has a single parameter whose
8545 // type-specifier is cv T followed by the abstract-declarator. [...]
8546 //
8547 // The cv part is done in the calling function - we get the concept with
8548 // arguments and the abstract declarator with the correct CV qualification and
8549 // have to synthesize T and the single parameter of F.
8550 auto &II = Context.Idents.get("expr-type");
8551 auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,
8552 SourceLocation(),
8553 SourceLocation(), Depth,
8554 /*Index=*/0, &II,
8555 /*Typename=*/true,
8556 /*ParameterPack=*/false,
8557 /*HasTypeConstraint=*/true);
8558
8559 if (ActOnTypeConstraint(SS, TypeConstraint, TParam,
8560 /*EllpsisLoc=*/SourceLocation()))
8561 // Just produce a requirement with no type requirements.
8562 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
8563
8564 auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),
8565 SourceLocation(),
8566 ArrayRef<NamedDecl *>(TParam),
8567 SourceLocation(),
8568 /*RequiresClause=*/nullptr);
8569 return BuildExprRequirement(
8570 E, /*IsSimple=*/false, NoexceptLoc,
8571 concepts::ExprRequirement::ReturnTypeRequirement(TPL));
8572}
8573
8574concepts::ExprRequirement *
8575Sema::BuildExprRequirement(
8576 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
8577 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8578 auto Status = concepts::ExprRequirement::SS_Satisfied;
8579 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
8580 if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent())
8581 Status = concepts::ExprRequirement::SS_Dependent;
8582 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
8583 Status = concepts::ExprRequirement::SS_NoexceptNotMet;
8584 else if (ReturnTypeRequirement.isSubstitutionFailure())
8585 Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;
8586 else if (ReturnTypeRequirement.isTypeConstraint()) {
8587 // C++2a [expr.prim.req]p1.3.3
8588 // The immediately-declared constraint ([temp]) of decltype((E)) shall
8589 // be satisfied.
8590 TemplateParameterList *TPL =
8591 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
8592 QualType MatchedType =
8593 BuildDecltypeType(E, E->getBeginLoc()).getCanonicalType();
8594 llvm::SmallVector<TemplateArgument, 1> Args;
8595 Args.push_back(TemplateArgument(MatchedType));
8596 TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args);
8597 MultiLevelTemplateArgumentList MLTAL(TAL);
8598 for (unsigned I = 0; I < TPL->getDepth(); ++I)
8599 MLTAL.addOuterRetainedLevel();
8600 Expr *IDC =
8601 cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint()
8602 ->getImmediatelyDeclaredConstraint();
8603 ExprResult Constraint = SubstExpr(IDC, MLTAL);
8604 assert(!Constraint.isInvalid() &&
8605 "Substitution cannot fail as it is simply putting a type template "
8606 "argument into a concept specialization expression's parameter.");
8607
8608 SubstitutedConstraintExpr =
8609 cast<ConceptSpecializationExpr>(Constraint.get());
8610 if (!SubstitutedConstraintExpr->isSatisfied())
8611 Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
8612 }
8613 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
8614 ReturnTypeRequirement, Status,
8615 SubstitutedConstraintExpr);
8616}
8617
8618concepts::ExprRequirement *
8619Sema::BuildExprRequirement(
8620 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
8621 bool IsSimple, SourceLocation NoexceptLoc,
8622 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8623 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
8624 IsSimple, NoexceptLoc,
8625 ReturnTypeRequirement);
8626}
8627
8628concepts::TypeRequirement *
8629Sema::BuildTypeRequirement(TypeSourceInfo *Type) {
8630 return new (Context) concepts::TypeRequirement(Type);
8631}
8632
8633concepts::TypeRequirement *
8634Sema::BuildTypeRequirement(
8635 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
8636 return new (Context) concepts::TypeRequirement(SubstDiag);
8637}
8638
8639concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {
8640 return BuildNestedRequirement(Constraint);
8641}
8642
8643concepts::NestedRequirement *
8644Sema::BuildNestedRequirement(Expr *Constraint) {
8645 ConstraintSatisfaction Satisfaction;
8646 if (!Constraint->isInstantiationDependent() &&
Saar Raz713562f2020-01-25 22:54:27 +02008647 CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
8648 Constraint->getSourceRange(), Satisfaction))
Saar Raza0f50d72020-01-18 09:11:43 +02008649 return nullptr;
8650 return new (Context) concepts::NestedRequirement(Context, Constraint,
8651 Satisfaction);
8652}
8653
8654concepts::NestedRequirement *
8655Sema::BuildNestedRequirement(
8656 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
8657 return new (Context) concepts::NestedRequirement(SubstDiag);
8658}
8659
8660RequiresExprBodyDecl *
8661Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8662 ArrayRef<ParmVarDecl *> LocalParameters,
8663 Scope *BodyScope) {
8664 assert(BodyScope);
8665
8666 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,
8667 RequiresKWLoc);
8668
8669 PushDeclContext(BodyScope, Body);
8670
8671 for (ParmVarDecl *Param : LocalParameters) {
8672 if (Param->hasDefaultArg())
8673 // C++2a [expr.prim.req] p4
8674 // [...] A local parameter of a requires-expression shall not have a
8675 // default argument. [...]
8676 Diag(Param->getDefaultArgRange().getBegin(),
8677 diag::err_requires_expr_local_parameter_default_argument);
8678 // Ignore default argument and move on
8679
8680 Param->setDeclContext(Body);
8681 // If this has an identifier, add it to the scope stack.
8682 if (Param->getIdentifier()) {
8683 CheckShadow(BodyScope, Param);
8684 PushOnScopeChains(Param, BodyScope);
8685 }
8686 }
8687 return Body;
8688}
8689
8690void Sema::ActOnFinishRequiresExpr() {
8691 assert(CurContext && "DeclContext imbalance!");
8692 CurContext = CurContext->getLexicalParent();
8693 assert(CurContext && "Popped translation unit!");
8694}
8695
8696ExprResult
8697Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8698 RequiresExprBodyDecl *Body,
8699 ArrayRef<ParmVarDecl *> LocalParameters,
8700 ArrayRef<concepts::Requirement *> Requirements,
8701 SourceLocation ClosingBraceLoc) {
8702 return RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters,
8703 Requirements, ClosingBraceLoc);
8704}