Bug Summary

File:clang/lib/Sema/SemaExprCXX.cpp
Warning:line 1231, column 28
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaExprCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/include -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-06-21-164211-33944-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp

/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp

1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// Implements semantic analysis for C++ expressions.
11///
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/Template.h"
15#include "clang/Sema/SemaInternal.h"
16#include "TreeTransform.h"
17#include "TypeLocBuilder.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/CharUnits.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/RecursiveASTVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/AlignedAllocation.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#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"
37#include "clang/Sema/SemaLambda.h"
38#include "clang/Sema/TemplateDeduction.h"
39#include "llvm/ADT/APInt.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/Support/ErrorHandling.h"
42using namespace clang;
43using namespace sema;
44
45/// Handle the result of the special case name lookup for inheriting
46/// 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")(static_cast <bool> (NNS->getAsIdentifier() == &
Name && "not a constructor name") ? void (0) : __assert_fail
("NNS->getAsIdentifier() == &Name && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 65, __extension__ __PRETTY_FUNCTION__))
;
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
68 break;
69
70 case NestedNameSpecifier::Global:
71 case NestedNameSpecifier::Super:
72 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor")::llvm::llvm_unreachable_internal("Nested name specifier is not a type for inheriting ctor"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 74)
;
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
83ParsedType Sema::getConstructorName(IdentifierInfo &II,
84 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 bool EnteringContext) {
87 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88 assert(CurClass && &II == CurClass->getIdentifier() &&(static_cast <bool> (CurClass && &II == CurClass
->getIdentifier() && "not a constructor name") ? void
(0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 89, __extension__ __PRETTY_FUNCTION__))
89 "not a constructor name")(static_cast <bool> (CurClass && &II == CurClass
->getIdentifier() && "not a constructor name") ? void
(0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 89, __extension__ __PRETTY_FUNCTION__))
;
90
91 // When naming a constructor as a member of a dependent context (eg, in a
92 // friend declaration or an inherited constructor declaration), form an
93 // unresolved "typename" type.
94 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
95 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96 return ParsedType::make(T);
97 }
98
99 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 }
116 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 }
123 return ParsedType();
124 }
125
126 QualType T = Context.getTypeDeclType(InjectedClassName);
127 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
129
130 return ParsedType::make(T);
131}
132
133ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
134 IdentifierInfo &II,
135 SourceLocation NameLoc,
136 Scope *S, CXXScopeSpec &SS,
137 ParsedType ObjectTypePtr,
138 bool EnteringContext) {
139 // 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 //
158 // See also PR6358 and PR6359.
159 //
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.
167
168 if (SS.isInvalid())
169 return nullptr;
170
171 // Whether we've failed with a diagnostic already.
172 bool Failed = false;
173
174 llvm::SmallVector<NamedDecl*, 8> FoundDecls;
175 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
176
177 // 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.
180 QualType SearchType =
181 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
182
183 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
184 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
185 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
186 if (!Type)
187 return false;
188
189 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;
197 for (NamedDecl *D : Found) {
198 if (IsAcceptableResult(D))
199 ++NumAcceptableResults;
200
201 // 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 }
211
212 // 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
237 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
238 if (IsAcceptableResult(Type)) {
239 QualType T = Context.getTypeDeclType(Type);
240 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
241 return CreateParsedType(T,
242 Context.getTrivialTypeSourceInfo(T, NameLoc));
243 }
244 }
245
246 return nullptr;
247 };
248
249 bool IsDependent = false;
250
251 auto LookupInObjectType = [&]() -> ParsedType {
252 if (Failed || SearchType.isNull())
253 return nullptr;
254
255 IsDependent |= SearchType->isDependentType();
256
257 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
258 DeclContext *LookupCtx = computeDeclContext(SearchType);
259 if (!LookupCtx)
260 return nullptr;
261 LookupQualifiedName(Found, LookupCtx);
262 return CheckLookupResult(Found);
263 };
264
265 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
266 if (Failed)
267 return nullptr;
268
269 IsDependent |= isDependentScopeSpecifier(LookupSS);
270 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
271 if (!LookupCtx)
272 return nullptr;
273
274 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
275 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
276 Failed = true;
277 return nullptr;
278 }
279 LookupQualifiedName(Found, LookupCtx);
280 return CheckLookupResult(Found);
281 };
282
283 auto LookupInScope = [&]() -> ParsedType {
284 if (Failed || !S)
285 return nullptr;
286
287 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
288 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;
349 }
350
351 if (Failed)
352 return nullptr;
353
354 if (IsDependent) {
355 // We didn't find our type, but that's OK: it's dependent anyway.
356
357 // FIXME: What if we have no nested-name-specifier?
358 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
359 SS.getWithLocInContext(Context),
360 II, NameLoc);
361 return ParsedType::make(T);
362 }
363
364 // 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;
380 }
381
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() &&(static_cast <bool> (!SearchType.isNull() && "should only reject a type result if we have a search type"
) ? void (0) : __assert_fail ("!SearchType.isNull() && \"should only reject a type result if we have a search type\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 433, __extension__ __PRETTY_FUNCTION__))
433 "should only reject a type result if we have a search type")(static_cast <bool> (!SearchType.isNull() && "should only reject a type result if we have a search type"
) ? void (0) : __assert_fail ("!SearchType.isNull() && \"should only reject a type result if we have a search type\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 433, __extension__ __PRETTY_FUNCTION__))
;
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;
454 }
455
456 return nullptr;
457}
458
459ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
460 ParsedType ObjectType) {
461 if (DS.getTypeSpecType() == DeclSpec::TST_error)
462 return nullptr;
463
464 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 &&(static_cast <bool> (DS.getTypeSpecType() == DeclSpec::
TST_decltype && "unexpected type in getDestructorType"
) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 470, __extension__ __PRETTY_FUNCTION__))
470 "unexpected type in getDestructorType")(static_cast <bool> (DS.getTypeSpecType() == DeclSpec::
TST_decltype && "unexpected type in getDestructorType"
) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 470, __extension__ __PRETTY_FUNCTION__))
;
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)) {
478 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
479 << T << SearchType;
480 return nullptr;
481 }
482
483 return ParsedType::make(T);
484}
485
486bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
487 const UnqualifiedId &Name) {
488 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId)(static_cast <bool> (Name.getKind() == UnqualifiedIdKind
::IK_LiteralOperatorId) ? void (0) : __assert_fail ("Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 488, __extension__ __PRETTY_FUNCTION__))
;
489
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.
501 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
502 << SS.getScopeRep();
503 return true;
504
505 case NestedNameSpecifier::Global:
506 case NestedNameSpecifier::Super:
507 case NestedNameSpecifier::Namespace:
508 case NestedNameSpecifier::NamespaceAlias:
509 return false;
510 }
511
512 llvm_unreachable("unknown nested name specifier kind")::llvm::llvm_unreachable_internal("unknown nested name specifier kind"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 512)
;
513}
514
515/// Build a C++ typeid expression with a type operand.
516ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
517 SourceLocation TypeidLoc,
518 TypeSourceInfo *Operand,
519 SourceLocation RParenLoc) {
520 // C++ [expr.typeid]p4:
521 // The top-level cv-qualifiers of the lvalue expression or the type-id
522 // that is the operand of typeid are always ignored.
523 // If the type of the type-id is a class type or a reference to a class
524 // type, the class shall be completely-defined.
525 Qualifiers Quals;
526 QualType T
527 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
528 Quals);
529 if (T->getAs<RecordType>() &&
530 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
531 return ExprError();
532
533 if (T->isVariablyModifiedType())
534 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
535
536 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
537 return ExprError();
538
539 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
540 SourceRange(TypeidLoc, RParenLoc));
541}
542
543/// Build a C++ typeid expression with an expression operand.
544ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
545 SourceLocation TypeidLoc,
546 Expr *E,
547 SourceLocation RParenLoc) {
548 bool WasEvaluated = false;
549 if (E && !E->isTypeDependent()) {
550 if (E->getType()->isPlaceholderType()) {
551 ExprResult result = CheckPlaceholderExpr(E);
552 if (result.isInvalid()) return ExprError();
553 E = result.get();
554 }
555
556 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();
564
565 // C++ [expr.typeid]p3:
566 // When typeid is applied to an expression other than an glvalue of a
567 // polymorphic class type [...] [the] expression is an unevaluated
568 // operand. [...]
569 if (RecordD->isPolymorphic() && E->isGLValue()) {
570 if (isUnevaluatedContext()) {
571 // The operand was processed in unevaluated context, switch the
572 // context and recheck the subexpression.
573 ExprResult Result = TransformToPotentiallyEvaluated(E);
574 if (Result.isInvalid())
575 return ExprError();
576 E = Result.get();
577 }
578
579 // We require a vtable to query the type at run time.
580 MarkVTableUsed(TypeidLoc, RecordD);
581 WasEvaluated = true;
582 }
583 }
584
585 ExprResult Result = CheckUnevaluatedOperand(E);
586 if (Result.isInvalid())
587 return ExprError();
588 E = Result.get();
589
590 // C++ [expr.typeid]p4:
591 // [...] If the type of the type-id is a reference to a possibly
592 // cv-qualified type, the result of the typeid expression refers to a
593 // std::type_info object representing the cv-unqualified referenced
594 // type.
595 Qualifiers Quals;
596 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
597 if (!Context.hasSameType(T, UnqualT)) {
598 T = UnqualT;
599 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
600 }
601 }
602
603 if (E->getType()->isVariablyModifiedType())
604 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
605 << E->getType());
606 else if (!inTemplateInstantiation() &&
607 E->HasSideEffects(Context, WasEvaluated)) {
608 // The expression operand for typeid is in an unevaluated expression
609 // context, so side effects could result in unintended consequences.
610 Diag(E->getExprLoc(), WasEvaluated
611 ? diag::warn_side_effects_typeid
612 : diag::warn_side_effects_unevaluated_context);
613 }
614
615 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
616 SourceRange(TypeidLoc, RParenLoc));
617}
618
619/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
620ExprResult
621Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
622 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
623 // typeid is not supported in OpenCL.
624 if (getLangOpts().OpenCLCPlusPlus) {
625 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
626 << "typeid");
627 }
628
629 // Find the std::type_info type.
630 if (!getStdNamespace())
631 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
632
633 if (!CXXTypeInfoDecl) {
634 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
635 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
636 LookupQualifiedName(R, getStdNamespace());
637 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
638 // Microsoft's typeinfo doesn't have type_info in std but in the global
639 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
640 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
641 LookupQualifiedName(R, Context.getTranslationUnitDecl());
642 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
643 }
644 if (!CXXTypeInfoDecl)
645 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
646 }
647
648 if (!getLangOpts().RTTI) {
649 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
650 }
651
652 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
653
654 if (isType) {
655 // The operand is a type; handle it as such.
656 TypeSourceInfo *TInfo = nullptr;
657 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
658 &TInfo);
659 if (T.isNull())
660 return ExprError();
661
662 if (!TInfo)
663 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
664
665 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
666 }
667
668 // The operand is an expression.
669 ExprResult Result =
670 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
671
672 if (!getLangOpts().RTTIData && !Result.isInvalid())
673 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
674 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
675 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
676 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
677 DiagnosticOptions::MSVC);
678 return Result;
679}
680
681/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
682/// a single GUID.
683static void
684getUuidAttrOfType(Sema &SemaRef, QualType QT,
685 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
686 // Optionally remove one level of pointer, reference or array indirection.
687 const Type *Ty = QT.getTypePtr();
688 if (QT->isPointerType() || QT->isReferenceType())
689 Ty = QT->getPointeeType().getTypePtr();
690 else if (QT->isArrayType())
691 Ty = Ty->getBaseElementTypeUnsafe();
692
693 const auto *TD = Ty->getAsTagDecl();
694 if (!TD)
695 return;
696
697 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
698 UuidAttrs.insert(Uuid);
699 return;
700 }
701
702 // __uuidof can grab UUIDs from template arguments.
703 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
704 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
705 for (const TemplateArgument &TA : TAL.asArray()) {
706 const UuidAttr *UuidForTA = nullptr;
707 if (TA.getKind() == TemplateArgument::Type)
708 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
709 else if (TA.getKind() == TemplateArgument::Declaration)
710 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
711
712 if (UuidForTA)
713 UuidAttrs.insert(UuidForTA);
714 }
715 }
716}
717
718/// Build a Microsoft __uuidof expression with a type operand.
719ExprResult Sema::BuildCXXUuidof(QualType Type,
720 SourceLocation TypeidLoc,
721 TypeSourceInfo *Operand,
722 SourceLocation RParenLoc) {
723 MSGuidDecl *Guid = nullptr;
724 if (!Operand->getType()->isDependentType()) {
725 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
726 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
727 if (UuidAttrs.empty())
728 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
729 if (UuidAttrs.size() > 1)
730 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
731 Guid = UuidAttrs.back()->getGuidDecl();
732 }
733
734 return new (Context)
735 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
736}
737
738/// Build a Microsoft __uuidof expression with an expression operand.
739ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,
740 Expr *E, SourceLocation RParenLoc) {
741 MSGuidDecl *Guid = nullptr;
742 if (!E->getType()->isDependentType()) {
743 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
744 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
745 Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});
746 } else {
747 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
748 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
749 if (UuidAttrs.empty())
750 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
751 if (UuidAttrs.size() > 1)
752 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
753 Guid = UuidAttrs.back()->getGuidDecl();
754 }
755 }
756
757 return new (Context)
758 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
759}
760
761/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
762ExprResult
763Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
764 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
765 QualType GuidType = Context.getMSGuidType();
766 GuidType.addConst();
767
768 if (isType) {
769 // The operand is a type; handle it as such.
770 TypeSourceInfo *TInfo = nullptr;
771 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
772 &TInfo);
773 if (T.isNull())
774 return ExprError();
775
776 if (!TInfo)
777 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
778
779 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
780 }
781
782 // The operand is an expression.
783 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
784}
785
786/// ActOnCXXBoolLiteral - Parse {true,false} literals.
787ExprResult
788Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
789 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&(static_cast <bool> ((Kind == tok::kw_true || Kind == tok
::kw_false) && "Unknown C++ Boolean value!") ? void (
0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 790, __extension__ __PRETTY_FUNCTION__))
790 "Unknown C++ Boolean value!")(static_cast <bool> ((Kind == tok::kw_true || Kind == tok
::kw_false) && "Unknown C++ Boolean value!") ? void (
0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 790, __extension__ __PRETTY_FUNCTION__))
;
791 return new (Context)
792 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
793}
794
795/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
796ExprResult
797Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
798 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
799}
800
801/// ActOnCXXThrow - Parse throw expressions.
802ExprResult
803Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
804 bool IsThrownVarInScope = false;
805 if (Ex) {
806 // C++0x [class.copymove]p31:
807 // When certain criteria are met, an implementation is allowed to omit the
808 // copy/move construction of a class object [...]
809 //
810 // - in a throw-expression, when the operand is the name of a
811 // non-volatile automatic object (other than a function or catch-
812 // clause parameter) whose scope does not extend beyond the end of the
813 // innermost enclosing try-block (if there is one), the copy/move
814 // operation from the operand to the exception object (15.1) can be
815 // omitted by constructing the automatic object directly into the
816 // exception object
817 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
818 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
819 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
820 for( ; S; S = S->getParent()) {
821 if (S->isDeclScope(Var)) {
822 IsThrownVarInScope = true;
823 break;
824 }
825
826 if (S->getFlags() &
827 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
828 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
829 Scope::TryScope))
830 break;
831 }
832 }
833 }
834 }
835
836 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
837}
838
839ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
840 bool IsThrownVarInScope) {
841 // Don't report an error if 'throw' is used in system headers.
842 if (!getLangOpts().CXXExceptions &&
843 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
844 // Delay error emission for the OpenMP device code.
845 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
846 }
847
848 // Exceptions aren't allowed in CUDA device code.
849 if (getLangOpts().CUDA)
850 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
851 << "throw" << CurrentCUDATarget();
852
853 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
854 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
855
856 if (Ex && !Ex->isTypeDependent()) {
857 // Initialize the exception result. This implicitly weeds out
858 // abstract types or types with inaccessible copy constructors.
859
860 // C++0x [class.copymove]p31:
861 // When certain criteria are met, an implementation is allowed to omit the
862 // copy/move construction of a class object [...]
863 //
864 // - in a throw-expression, when the operand is the name of a
865 // non-volatile automatic object (other than a function or
866 // catch-clause
867 // parameter) whose scope does not extend beyond the end of the
868 // innermost enclosing try-block (if there is one), the copy/move
869 // operation from the operand to the exception object (15.1) can be
870 // omitted by constructing the automatic object directly into the
871 // exception object
872 NamedReturnInfo NRInfo =
873 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
874
875 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
876 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
877 return ExprError();
878
879 InitializedEntity Entity = InitializedEntity::InitializeException(
880 OpLoc, ExceptionObjectTy,
881 /*NRVO=*/NRInfo.isCopyElidable());
882 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
883 if (Res.isInvalid())
884 return ExprError();
885 Ex = Res.get();
886 }
887
888 // PPC MMA non-pointer types are not allowed as throw expr types.
889 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
890 CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
891
892 return new (Context)
893 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
894}
895
896static void
897collectPublicBases(CXXRecordDecl *RD,
898 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
899 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
900 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
901 bool ParentIsPublic) {
902 for (const CXXBaseSpecifier &BS : RD->bases()) {
903 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
904 bool NewSubobject;
905 // Virtual bases constitute the same subobject. Non-virtual bases are
906 // always distinct subobjects.
907 if (BS.isVirtual())
908 NewSubobject = VBases.insert(BaseDecl).second;
909 else
910 NewSubobject = true;
911
912 if (NewSubobject)
913 ++SubobjectsSeen[BaseDecl];
914
915 // Only add subobjects which have public access throughout the entire chain.
916 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
917 if (PublicPath)
918 PublicSubobjectsSeen.insert(BaseDecl);
919
920 // Recurse on to each base subobject.
921 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
922 PublicPath);
923 }
924}
925
926static void getUnambiguousPublicSubobjects(
927 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
928 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
929 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
930 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
931 SubobjectsSeen[RD] = 1;
932 PublicSubobjectsSeen.insert(RD);
933 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
934 /*ParentIsPublic=*/true);
935
936 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
937 // Skip ambiguous objects.
938 if (SubobjectsSeen[PublicSubobject] > 1)
939 continue;
940
941 Objects.push_back(PublicSubobject);
942 }
943}
944
945/// CheckCXXThrowOperand - Validate the operand of a throw.
946bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
947 QualType ExceptionObjectTy, Expr *E) {
948 // If the type of the exception would be an incomplete type or a pointer
949 // to an incomplete type other than (cv) void the program is ill-formed.
950 QualType Ty = ExceptionObjectTy;
951 bool isPointer = false;
952 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
953 Ty = Ptr->getPointeeType();
954 isPointer = true;
955 }
956 if (!isPointer || !Ty->isVoidType()) {
957 if (RequireCompleteType(ThrowLoc, Ty,
958 isPointer ? diag::err_throw_incomplete_ptr
959 : diag::err_throw_incomplete,
960 E->getSourceRange()))
961 return true;
962
963 if (!isPointer && Ty->isSizelessType()) {
964 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
965 return true;
966 }
967
968 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
969 diag::err_throw_abstract_type, E))
970 return true;
971 }
972
973 // If the exception has class type, we need additional handling.
974 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
975 if (!RD)
976 return false;
977
978 // If we are throwing a polymorphic class type or pointer thereof,
979 // exception handling will make use of the vtable.
980 MarkVTableUsed(ThrowLoc, RD);
981
982 // If a pointer is thrown, the referenced object will not be destroyed.
983 if (isPointer)
984 return false;
985
986 // If the class has a destructor, we must be able to call it.
987 if (!RD->hasIrrelevantDestructor()) {
988 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
989 MarkFunctionReferenced(E->getExprLoc(), Destructor);
990 CheckDestructorAccess(E->getExprLoc(), Destructor,
991 PDiag(diag::err_access_dtor_exception) << Ty);
992 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
993 return true;
994 }
995 }
996
997 // The MSVC ABI creates a list of all types which can catch the exception
998 // object. This list also references the appropriate copy constructor to call
999 // if the object is caught by value and has a non-trivial copy constructor.
1000 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1001 // We are only interested in the public, unambiguous bases contained within
1002 // the exception object. Bases which are ambiguous or otherwise
1003 // inaccessible are not catchable types.
1004 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1005 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1006
1007 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1008 // Attempt to lookup the copy constructor. Various pieces of machinery
1009 // will spring into action, like template instantiation, which means this
1010 // cannot be a simple walk of the class's decls. Instead, we must perform
1011 // lookup and overload resolution.
1012 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1013 if (!CD || CD->isDeleted())
1014 continue;
1015
1016 // Mark the constructor referenced as it is used by this throw expression.
1017 MarkFunctionReferenced(E->getExprLoc(), CD);
1018
1019 // Skip this copy constructor if it is trivial, we don't need to record it
1020 // in the catchable type data.
1021 if (CD->isTrivial())
1022 continue;
1023
1024 // The copy constructor is non-trivial, create a mapping from this class
1025 // type to this constructor.
1026 // N.B. The selection of copy constructor is not sensitive to this
1027 // particular throw-site. Lookup will be performed at the catch-site to
1028 // ensure that the copy constructor is, in fact, accessible (via
1029 // friendship or any other means).
1030 Context.addCopyConstructorForExceptionObject(Subobject, CD);
1031
1032 // We don't keep the instantiated default argument expressions around so
1033 // we must rebuild them here.
1034 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1035 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1036 return true;
1037 }
1038 }
1039 }
1040
1041 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1042 // the runtime with no ability for the compiler to request additional
1043 // alignment. Warn if the exception type requires alignment beyond the minimum
1044 // guaranteed by the target C++ runtime.
1045 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1046 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1047 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1048 if (ExnObjAlign < TypeAlign) {
1049 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1050 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1051 << Ty << (unsigned)TypeAlign.getQuantity()
1052 << (unsigned)ExnObjAlign.getQuantity();
1053 }
1054 }
1055
1056 return false;
1057}
1058
1059static QualType adjustCVQualifiersForCXXThisWithinLambda(
1060 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1061 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1062
1063 QualType ClassType = ThisTy->getPointeeType();
1064 LambdaScopeInfo *CurLSI = nullptr;
1065 DeclContext *CurDC = CurSemaContext;
1066
1067 // Iterate through the stack of lambdas starting from the innermost lambda to
1068 // the outermost lambda, checking if '*this' is ever captured by copy - since
1069 // that could change the cv-qualifiers of the '*this' object.
1070 // The object referred to by '*this' starts out with the cv-qualifiers of its
1071 // member function. We then start with the innermost lambda and iterate
1072 // outward checking to see if any lambda performs a by-copy capture of '*this'
1073 // - and if so, any nested lambda must respect the 'constness' of that
1074 // capturing lamdbda's call operator.
1075 //
1076
1077 // Since the FunctionScopeInfo stack is representative of the lexical
1078 // nesting of the lambda expressions during initial parsing (and is the best
1079 // place for querying information about captures about lambdas that are
1080 // partially processed) and perhaps during instantiation of function templates
1081 // that contain lambda expressions that need to be transformed BUT not
1082 // necessarily during instantiation of a nested generic lambda's function call
1083 // operator (which might even be instantiated at the end of the TU) - at which
1084 // time the DeclContext tree is mature enough to query capture information
1085 // reliably - we use a two pronged approach to walk through all the lexically
1086 // enclosing lambda expressions:
1087 //
1088 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1089 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1090 // enclosed by the call-operator of the LSI below it on the stack (while
1091 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1092 // the stack represents the innermost lambda.
1093 //
1094 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1095 // represents a lambda's call operator. If it does, we must be instantiating
1096 // a generic lambda's call operator (represented by the Current LSI, and
1097 // should be the only scenario where an inconsistency between the LSI and the
1098 // DeclContext should occur), so climb out the DeclContexts if they
1099 // represent lambdas, while querying the corresponding closure types
1100 // regarding capture information.
1101
1102 // 1) Climb down the function scope info stack.
1103 for (int I = FunctionScopes.size();
1104 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1105 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1106 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1107 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1108 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1109
1110 if (!CurLSI->isCXXThisCaptured())
1111 continue;
1112
1113 auto C = CurLSI->getCXXThisCapture();
1114
1115 if (C.isCopyCapture()) {
1116 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1117 if (CurLSI->CallOperator->isConst())
1118 ClassType.addConst();
1119 return ASTCtx.getPointerType(ClassType);
1120 }
1121 }
1122
1123 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1124 // happen during instantiation of its nested generic lambda call operator)
1125 if (isLambdaCallOperator(CurDC)) {
1126 assert(CurLSI && "While computing 'this' capture-type for a generic "(static_cast <bool> (CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? void
(0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1127, __extension__ __PRETTY_FUNCTION__))
1127 "lambda, we must have a corresponding LambdaScopeInfo")(static_cast <bool> (CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? void
(0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1127, __extension__ __PRETTY_FUNCTION__))
;
1128 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&(static_cast <bool> (isGenericLambdaCallOperatorSpecialization
(CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1132, __extension__ __PRETTY_FUNCTION__))
1129 "While computing 'this' capture-type for a generic lambda, when we "(static_cast <bool> (isGenericLambdaCallOperatorSpecialization
(CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1132, __extension__ __PRETTY_FUNCTION__))
1130 "run out of enclosing LSI's, yet the enclosing DC is a "(static_cast <bool> (isGenericLambdaCallOperatorSpecialization
(CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1132, __extension__ __PRETTY_FUNCTION__))
1131 "lambda-call-operator we must be (i.e. Current LSI) in a generic "(static_cast <bool> (isGenericLambdaCallOperatorSpecialization
(CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1132, __extension__ __PRETTY_FUNCTION__))
1132 "lambda call oeprator")(static_cast <bool> (isGenericLambdaCallOperatorSpecialization
(CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1132, __extension__ __PRETTY_FUNCTION__))
;
1133 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator))(static_cast <bool> (CurDC == getLambdaAwareParentOfDeclContext
(CurLSI->CallOperator)) ? void (0) : __assert_fail ("CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1133, __extension__ __PRETTY_FUNCTION__))
;
1134
1135 auto IsThisCaptured =
1136 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1137 IsConst = false;
1138 IsByCopy = false;
1139 for (auto &&C : Closure->captures()) {
1140 if (C.capturesThis()) {
1141 if (C.getCaptureKind() == LCK_StarThis)
1142 IsByCopy = true;
1143 if (Closure->getLambdaCallOperator()->isConst())
1144 IsConst = true;
1145 return true;
1146 }
1147 }
1148 return false;
1149 };
1150
1151 bool IsByCopyCapture = false;
1152 bool IsConstCapture = false;
1153 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1154 while (Closure &&
1155 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1156 if (IsByCopyCapture) {
1157 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1158 if (IsConstCapture)
1159 ClassType.addConst();
1160 return ASTCtx.getPointerType(ClassType);
1161 }
1162 Closure = isLambdaCallOperator(Closure->getParent())
1163 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1164 : nullptr;
1165 }
1166 }
1167 return ASTCtx.getPointerType(ClassType);
1168}
1169
1170QualType Sema::getCurrentThisType() {
1171 DeclContext *DC = getFunctionLevelDeclContext();
1172 QualType ThisTy = CXXThisTypeOverride;
1173
1174 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1175 if (method && method->isInstance())
1176 ThisTy = method->getThisType();
1177 }
1178
1179 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1180 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1181
1182 // This is a lambda call operator that is being instantiated as a default
1183 // initializer. DC must point to the enclosing class type, so we can recover
1184 // the 'this' type from it.
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);
1189 }
1190
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);
1197 return ThisTy;
1198}
1199
1200Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1201 Decl *ContextDecl,
1202 Qualifiers CXXThisTypeQuals,
1203 bool Enabled)
1204 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1205{
1206 if (!Enabled || !ContextDecl)
1207 return;
1208
1209 CXXRecordDecl *Record = nullptr;
1210 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1211 Record = Template->getTemplatedDecl();
1212 else
1213 Record = cast<CXXRecordDecl>(ContextDecl);
1214
1215 QualType T = S.Context.getRecordType(Record);
1216 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1217
1218 S.CXXThisTypeOverride = S.Context.getPointerType(T);
1219
1220 this->Enabled = true;
1221}
1222
1223
1224Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1225 if (Enabled) {
1226 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1227 }
1228}
1229
1230static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) {
1231 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
32
Called C++ object pointer is null
1232 assert(!LSI->isCXXThisCaptured())(static_cast <bool> (!LSI->isCXXThisCaptured()) ? void
(0) : __assert_fail ("!LSI->isCXXThisCaptured()", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1232, __extension__ __PRETTY_FUNCTION__))
;
1233 // [=, this] {}; // until C++20: Error: this when = is the default
1234 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval &&
1235 !Sema.getLangOpts().CPlusPlus20)
1236 return;
1237 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1238 << FixItHint::CreateInsertion(
1239 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1240}
1241
1242bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1243 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1244 const bool ByCopy) {
1245 // We don't need to capture this in an unevaluated context.
1246 if (isUnevaluatedContext() && !Explicit)
5
Calling 'Sema::isUnevaluatedContext'
14
Returning from 'Sema::isUnevaluatedContext'
1247 return true;
1248
1249 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value")(static_cast <bool> ((!ByCopy || Explicit) && "cannot implicitly capture *this by value"
) ? void (0) : __assert_fail ("(!ByCopy || Explicit) && \"cannot implicitly capture *this by value\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1249, __extension__ __PRETTY_FUNCTION__))
;
15
'?' condition is true
1250
1251 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15.1
'FunctionScopeIndexToStopAt' is null
15.1
'FunctionScopeIndexToStopAt' is null
16
'?' condition is false
1252 ? *FunctionScopeIndexToStopAt 1253 : FunctionScopes.size() - 1; 1254 1255 // Check that we can capture the *enclosing object* (referred to by '*this') 1256 // by the capturing-entity/closure (lambda/block/etc) at 1257 // MaxFunctionScopesIndex-deep on the FunctionScopes stack. 1258 1259 // Note: The *enclosing object* can only be captured by-value by a 1260 // closure that is a lambda, using the explicit notation: 1261 // [*this] { ... }. 1262 // Every other capture of the *enclosing object* results in its by-reference 1263 // capture. 1264 1265 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes 1266 // stack), we can capture the *enclosing object* only if: 1267 // - 'L' has an explicit byref or byval capture of the *enclosing object* 1268 // - or, 'L' has an implicit capture. 1269 // AND 1270 // -- there is no enclosing closure 1271 // -- or, there is some enclosing closure 'E' that has already captured the 1272 // *enclosing object*, and every intervening closure (if any) between 'E' 1273 // and 'L' can implicitly capture the *enclosing object*. 1274 // -- or, every enclosing closure can implicitly capture the 1275 // *enclosing object* 1276 1277 1278 unsigned NumCapturingClosures = 0; 1279 for (int idx = MaxFunctionScopesIndex; idx
16.1
'idx' is >= 0
16.1
'idx' is >= 0
>= 0; idx--) {
17
Loop condition is true. Entering loop body
1280 if (CapturingScopeInfo *CSI
18.1
'CSI' is non-null
18.1
'CSI' is non-null
=
19
Taking true branch
1281 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
18
Assuming the object is a 'CapturingScopeInfo'
1282 if (CSI->CXXThisCaptureIndex != 0) {
20
Assuming field 'CXXThisCaptureIndex' is equal to 0
21
Taking false branch
1283 // 'this' is already being captured; there isn't anything more to do. 1284 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose); 1285 break; 1286 } 1287 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
22
Assuming 'CSI' is not a 'LambdaScopeInfo'
23
'LSI' initialized to a null pointer value
1288 if (LSI
23.1
'LSI' is null
23.1
'LSI' is null
&& isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { 1289 // This context can't implicitly capture 'this'; fail out. 1290 if (BuildAndDiagnose) { 1291 Diag(Loc, diag::err_this_capture) 1292 << (Explicit && idx == MaxFunctionScopesIndex); 1293 if (!Explicit) 1294 buildLambdaThisCaptureFixit(*this, LSI); 1295 } 1296 return true; 1297 } 1298 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
24
Assuming field 'ImpCaptureStyle' is not equal to ImpCap_LambdaByref
1299 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
25
Assuming field 'ImpCaptureStyle' is not equal to ImpCap_LambdaByval
1300 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
26
Assuming field 'ImpCaptureStyle' is not equal to ImpCap_Block
1301 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
27
Assuming field 'ImpCaptureStyle' is not equal to ImpCap_CapturedRegion
1302 (Explicit
27.1
'Explicit' is false
27.1
'Explicit' is false
&& idx == MaxFunctionScopesIndex)) { 1303 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first 1304 // iteration through can be an explicit capture, all enclosing closures, 1305 // if any, must perform implicit captures. 1306 1307 // This closure can capture 'this'; continue looking upwards. 1308 NumCapturingClosures++; 1309 continue; 1310 } 1311 // This context can't implicitly capture 'this'; fail out. 1312 if (BuildAndDiagnose
27.2
'BuildAndDiagnose' is true
27.2
'BuildAndDiagnose' is true
)
28
Taking true branch
1313 Diag(Loc, diag::err_this_capture) 1314 << (Explicit
28.1
'Explicit' is false
28.1
'Explicit' is false
&& idx == MaxFunctionScopesIndex); 1315 1316 if (!Explicit
28.2
'Explicit' is false
28.2
'Explicit' is false
)
29
Taking true branch
1317 buildLambdaThisCaptureFixit(*this, LSI);
30
Passing null pointer value via 2nd parameter 'LSI'
31
Calling 'buildLambdaThisCaptureFixit'
1318 return true; 1319 } 1320 break; 1321 } 1322 if (!BuildAndDiagnose) return false; 1323 1324 // If we got here, then the closure at MaxFunctionScopesIndex on the 1325 // FunctionScopes stack, can capture the *enclosing object*, so capture it 1326 // (including implicit by-reference captures in any enclosing closures). 1327 1328 // In the loop below, respect the ByCopy flag only for the closure requesting 1329 // the capture (i.e. first iteration through the loop below). Ignore it for 1330 // all enclosing closure's up to NumCapturingClosures (since they must be 1331 // implicitly capturing the *enclosing object* by reference (see loop 1332 // above)). 1333 assert((!ByCopy ||(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1336, __extension__ __PRETTY_FUNCTION__))
1334 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1336, __extension__ __PRETTY_FUNCTION__))
1335 "Only a lambda can capture the enclosing object (referred to by "(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1336, __extension__ __PRETTY_FUNCTION__))
1336 "*this) by copy")(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1336, __extension__ __PRETTY_FUNCTION__))
; 1337 QualType ThisTy = getCurrentThisType(); 1338 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; 1339 --idx, --NumCapturingClosures) { 1340 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); 1341 1342 // The type of the corresponding data member (not a 'this' pointer if 'by 1343 // copy'). 1344 QualType CaptureType = ThisTy; 1345 if (ByCopy) { 1346 // If we are capturing the object referred to by '*this' by copy, ignore 1347 // any cv qualifiers inherited from the type of the member function for 1348 // the type of the closure-type's corresponding data member and any use 1349 // of 'this'. 1350 CaptureType = ThisTy->getPointeeType(); 1351 CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 1352 } 1353 1354 bool isNested = NumCapturingClosures > 1; 1355 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); 1356 } 1357 return false; 1358} 1359 1360ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { 1361 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 1362 /// is a non-lvalue expression whose value is the address of the object for 1363 /// which the function is called. 1364 1365 QualType ThisTy = getCurrentThisType(); 1366 if (ThisTy.isNull())
1
Taking false branch
1367 return Diag(Loc, diag::err_invalid_this_use); 1368 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
2
Calling 'Sema::BuildCXXThisExpr'
1369} 1370 1371Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, 1372 bool IsImplicit) { 1373 auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit); 1374 MarkThisReferenced(This);
3
Calling 'Sema::MarkThisReferenced'
1375 return This; 1376} 1377 1378void Sema::MarkThisReferenced(CXXThisExpr *This) { 1379 CheckCXXThisCapture(This->getExprLoc());
4
Calling 'Sema::CheckCXXThisCapture'
1380} 1381 1382bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { 1383 // If we're outside the body of a member function, then we'll have a specified 1384 // type for 'this'. 1385 if (CXXThisTypeOverride.isNull()) 1386 return false; 1387 1388 // Determine whether we're looking into a class that's currently being 1389 // defined. 1390 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); 1391 return Class && Class->isBeingDefined(); 1392} 1393 1394/// Parse construction of a specified type. 1395/// Can be interpreted either as function-style casting ("int(x)") 1396/// or class type construction ("ClassType(x,y,z)") 1397/// or creation of a value-initialized type ("int()"). 1398ExprResult 1399Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 1400 SourceLocation LParenOrBraceLoc, 1401 MultiExprArg exprs, 1402 SourceLocation RParenOrBraceLoc, 1403 bool ListInitialization) { 1404 if (!TypeRep) 1405 return ExprError(); 1406 1407 TypeSourceInfo *TInfo; 1408 QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 1409 if (!TInfo) 1410 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 1411 1412 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs, 1413 RParenOrBraceLoc, ListInitialization); 1414 // Avoid creating a non-type-dependent expression that contains typos. 1415 // Non-type-dependent expressions are liable to be discarded without 1416 // checking for embedded typos. 1417 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && 1418 !Result.get()->isTypeDependent()) 1419 Result = CorrectDelayedTyposInExpr(Result.get()); 1420 else if (Result.isInvalid()) 1421 Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(), 1422 RParenOrBraceLoc, exprs, Ty); 1423 return Result; 1424} 1425 1426ExprResult 1427Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 1428 SourceLocation LParenOrBraceLoc, 1429 MultiExprArg Exprs, 1430 SourceLocation RParenOrBraceLoc, 1431 bool ListInitialization) { 1432 QualType Ty = TInfo->getType(); 1433 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 1434 1435 assert((!ListInitialization ||(static_cast <bool> ((!ListInitialization || (Exprs.size
() == 1 && isa<InitListExpr>(Exprs[0]))) &&
"List initialization must have initializer list as expression."
) ? void (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1437, __extension__ __PRETTY_FUNCTION__))
1436 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&(static_cast <bool> ((!ListInitialization || (Exprs.size
() == 1 && isa<InitListExpr>(Exprs[0]))) &&
"List initialization must have initializer list as expression."
) ? void (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1437, __extension__ __PRETTY_FUNCTION__))
1437 "List initialization must have initializer list as expression.")(static_cast <bool> ((!ListInitialization || (Exprs.size
() == 1 && isa<InitListExpr>(Exprs[0]))) &&
"List initialization must have initializer list as expression."
) ? void (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1437, __extension__ __PRETTY_FUNCTION__))
; 1438 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); 1439 1440 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo); 1441 InitializationKind Kind = 1442 Exprs.size() 1443 ? ListInitialization 1444 ? InitializationKind::CreateDirectList( 1445 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc) 1446 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc, 1447 RParenOrBraceLoc) 1448 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc, 1449 RParenOrBraceLoc); 1450 1451 // C++1z [expr.type.conv]p1: 1452 // If the type is a placeholder for a deduced class type, [...perform class 1453 // template argument deduction...] 1454 DeducedType *Deduced = Ty->getContainedDeducedType(); 1455 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { 1456 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, 1457 Kind, Exprs); 1458 if (Ty.isNull()) 1459 return ExprError(); 1460 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); 1461 } 1462 1463 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) { 1464 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization 1465 // directly. We work around this by dropping the locations of the braces. 1466 SourceRange Locs = ListInitialization 1467 ? SourceRange() 1468 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 1469 return CXXUnresolvedConstructExpr::Create(Context, Ty.getNonReferenceType(), 1470 TInfo, Locs.getBegin(), Exprs, 1471 Locs.getEnd()); 1472 } 1473 1474 // C++ [expr.type.conv]p1: 1475 // If the expression list is a parenthesized single expression, the type 1476 // conversion expression is equivalent (in definedness, and if defined in 1477 // meaning) to the corresponding cast expression. 1478 if (Exprs.size() == 1 && !ListInitialization && 1479 !isa<InitListExpr>(Exprs[0])) { 1480 Expr *Arg = Exprs[0]; 1481 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg, 1482 RParenOrBraceLoc); 1483 } 1484 1485 // For an expression of the form T(), T shall not be an array type. 1486 QualType ElemTy = Ty; 1487 if (Ty->isArrayType()) { 1488 if (!ListInitialization) 1489 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) 1490 << FullRange); 1491 ElemTy = Context.getBaseElementType(Ty); 1492 } 1493 1494 // There doesn't seem to be an explicit rule against this but sanity demands 1495 // we only construct objects with object types. 1496 if (Ty->isFunctionType()) 1497 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) 1498 << Ty << FullRange); 1499 1500 // C++17 [expr.type.conv]p2: 1501 // If the type is cv void and the initializer is (), the expression is a 1502 // prvalue of the specified type that performs no initialization. 1503 if (!Ty->isVoidType() && 1504 RequireCompleteType(TyBeginLoc, ElemTy, 1505 diag::err_invalid_incomplete_type_use, FullRange)) 1506 return ExprError(); 1507 1508 // Otherwise, the expression is a prvalue of the specified type whose 1509 // result object is direct-initialized (11.6) with the initializer. 1510 InitializationSequence InitSeq(*this, Entity, Kind, Exprs); 1511 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); 1512 1513 if (Result.isInvalid()) 1514 return Result; 1515 1516 Expr *Inner = Result.get(); 1517 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) 1518 Inner = BTE->getSubExpr(); 1519 if (!isa<CXXTemporaryObjectExpr>(Inner) && 1520 !isa<CXXScalarValueInitExpr>(Inner)) { 1521 // If we created a CXXTemporaryObjectExpr, that node also represents the 1522 // functional cast. Otherwise, create an explicit cast to represent 1523 // the syntactic form of a functional-style cast that was used here. 1524 // 1525 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr 1526 // would give a more consistent AST representation than using a 1527 // CXXTemporaryObjectExpr. It's also weird that the functional cast 1528 // is sometimes handled by initialization and sometimes not. 1529 QualType ResultType = Result.get()->getType(); 1530 SourceRange Locs = ListInitialization 1531 ? SourceRange() 1532 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 1533 Result = CXXFunctionalCastExpr::Create( 1534 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp, 1535 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(), 1536 Locs.getBegin(), Locs.getEnd()); 1537 } 1538 1539 return Result; 1540} 1541 1542bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { 1543 // [CUDA] Ignore this function, if we can't call it. 1544 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext); 1545 if (getLangOpts().CUDA) { 1546 auto CallPreference = IdentifyCUDAPreference(Caller, Method); 1547 // If it's not callable at all, it's not the right function. 1548 if (CallPreference < CFP_WrongSide) 1549 return false; 1550 if (CallPreference == CFP_WrongSide) { 1551 // Maybe. We have to check if there are better alternatives. 1552 DeclContext::lookup_result R = 1553 Method->getDeclContext()->lookup(Method->getDeclName()); 1554 for (const auto *D : R) { 1555 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 1556 if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide) 1557 return false; 1558 } 1559 } 1560 // We've found no better variants. 1561 } 1562 } 1563 1564 SmallVector<const FunctionDecl*, 4> PreventedBy; 1565 bool Result = Method->isUsualDeallocationFunction(PreventedBy); 1566 1567 if (Result || !getLangOpts().CUDA || PreventedBy.empty()) 1568 return Result; 1569 1570 // In case of CUDA, return true if none of the 1-argument deallocator 1571 // functions are actually callable. 1572 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) { 1573 assert(FD->getNumParams() == 1 &&(static_cast <bool> (FD->getNumParams() == 1 &&
"Only single-operand functions should be in PreventedBy") ? void
(0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1574, __extension__ __PRETTY_FUNCTION__))
1574 "Only single-operand functions should be in PreventedBy")(static_cast <bool> (FD->getNumParams() == 1 &&
"Only single-operand functions should be in PreventedBy") ? void
(0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1574, __extension__ __PRETTY_FUNCTION__))
; 1575 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice; 1576 }); 1577} 1578 1579/// Determine whether the given function is a non-placement 1580/// deallocation function. 1581static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { 1582 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 1583 return S.isUsualDeallocationFunction(Method); 1584 1585 if (FD->getOverloadedOperator() != OO_Delete && 1586 FD->getOverloadedOperator() != OO_Array_Delete) 1587 return false; 1588 1589 unsigned UsualParams = 1; 1590 1591 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && 1592 S.Context.hasSameUnqualifiedType( 1593 FD->getParamDecl(UsualParams)->getType(), 1594 S.Context.getSizeType())) 1595 ++UsualParams; 1596 1597 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && 1598 S.Context.hasSameUnqualifiedType( 1599 FD->getParamDecl(UsualParams)->getType(), 1600 S.Context.getTypeDeclType(S.getStdAlignValT()))) 1601 ++UsualParams; 1602 1603 return UsualParams == FD->getNumParams(); 1604} 1605 1606namespace { 1607 struct UsualDeallocFnInfo { 1608 UsualDeallocFnInfo() : Found(), FD(nullptr) {} 1609 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found) 1610 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())), 1611 Destroying(false), HasSizeT(false), HasAlignValT(false), 1612 CUDAPref(Sema::CFP_Native) { 1613 // A function template declaration is never a usual deallocation function. 1614 if (!FD) 1615 return; 1616 unsigned NumBaseParams = 1; 1617 if (FD->isDestroyingOperatorDelete()) { 1618 Destroying = true; 1619 ++NumBaseParams; 1620 } 1621 1622 if (NumBaseParams < FD->getNumParams() && 1623 S.Context.hasSameUnqualifiedType( 1624 FD->getParamDecl(NumBaseParams)->getType(), 1625 S.Context.getSizeType())) { 1626 ++NumBaseParams; 1627 HasSizeT = true; 1628 } 1629 1630 if (NumBaseParams < FD->getNumParams() && 1631 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) { 1632 ++NumBaseParams; 1633 HasAlignValT = true; 1634 } 1635 1636 // In CUDA, determine how much we'd like / dislike to call this. 1637 if (S.getLangOpts().CUDA) 1638 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 1639 CUDAPref = S.IdentifyCUDAPreference(Caller, FD); 1640 } 1641 1642 explicit operator bool() const { return FD; } 1643 1644 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize, 1645 bool WantAlign) const { 1646 // C++ P0722: 1647 // A destroying operator delete is preferred over a non-destroying 1648 // operator delete. 1649 if (Destroying != Other.Destroying) 1650 return Destroying; 1651 1652 // C++17 [expr.delete]p10: 1653 // If the type has new-extended alignment, a function with a parameter 1654 // of type std::align_val_t is preferred; otherwise a function without 1655 // such a parameter is preferred 1656 if (HasAlignValT != Other.HasAlignValT) 1657 return HasAlignValT == WantAlign; 1658 1659 if (HasSizeT != Other.HasSizeT) 1660 return HasSizeT == WantSize; 1661 1662 // Use CUDA call preference as a tiebreaker. 1663 return CUDAPref > Other.CUDAPref; 1664 } 1665 1666 DeclAccessPair Found; 1667 FunctionDecl *FD; 1668 bool Destroying, HasSizeT, HasAlignValT; 1669 Sema::CUDAFunctionPreference CUDAPref; 1670 }; 1671} 1672 1673/// Determine whether a type has new-extended alignment. This may be called when 1674/// the type is incomplete (for a delete-expression with an incomplete pointee 1675/// type), in which case it will conservatively return false if the alignment is 1676/// not known. 1677static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { 1678 return S.getLangOpts().AlignedAllocation && 1679 S.getASTContext().getTypeAlignIfKnown(AllocType) > 1680 S.getASTContext().getTargetInfo().getNewAlign(); 1681} 1682 1683/// Select the correct "usual" deallocation function to use from a selection of 1684/// deallocation functions (either global or class-scope). 1685static UsualDeallocFnInfo resolveDeallocationOverload( 1686 Sema &S, LookupResult &R, bool WantSize, bool WantAlign, 1687 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { 1688 UsualDeallocFnInfo Best; 1689 1690 for (auto I = R.begin(), E = R.end(); I != E; ++I) { 1691 UsualDeallocFnInfo Info(S, I.getPair()); 1692 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) || 1693 Info.CUDAPref == Sema::CFP_Never) 1694 continue; 1695 1696 if (!Best) { 1697 Best = Info; 1698 if (BestFns) 1699 BestFns->push_back(Info); 1700 continue; 1701 } 1702 1703 if (Best.isBetterThan(Info, WantSize, WantAlign)) 1704 continue; 1705 1706 // If more than one preferred function is found, all non-preferred 1707 // functions are eliminated from further consideration. 1708 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign)) 1709 BestFns->clear(); 1710 1711 Best = Info; 1712 if (BestFns) 1713 BestFns->push_back(Info); 1714 } 1715 1716 return Best; 1717} 1718 1719/// Determine whether a given type is a class for which 'delete[]' would call 1720/// a member 'operator delete[]' with a 'size_t' parameter. This implies that 1721/// we need to store the array size (even if the type is 1722/// trivially-destructible). 1723static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, 1724 QualType allocType) { 1725 const RecordType *record = 1726 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); 1727 if (!record) return false; 1728 1729 // Try to find an operator delete[] in class scope. 1730 1731 DeclarationName deleteName = 1732 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); 1733 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); 1734 S.LookupQualifiedName(ops, record->getDecl()); 1735 1736 // We're just doing this for information. 1737 ops.suppressDiagnostics(); 1738 1739 // Very likely: there's no operator delete[]. 1740 if (ops.empty()) return false; 1741 1742 // If it's ambiguous, it should be illegal to call operator delete[] 1743 // on this thing, so it doesn't matter if we allocate extra space or not. 1744 if (ops.isAmbiguous()) return false; 1745 1746 // C++17 [expr.delete]p10: 1747 // If the deallocation functions have class scope, the one without a 1748 // parameter of type std::size_t is selected. 1749 auto Best = resolveDeallocationOverload( 1750 S, ops, /*WantSize*/false, 1751 /*WantAlign*/hasNewExtendedAlignment(S, allocType)); 1752 return Best && Best.HasSizeT; 1753} 1754 1755/// Parsed a C++ 'new' expression (C++ 5.3.4). 1756/// 1757/// E.g.: 1758/// @code new (memory) int[size][4] @endcode 1759/// or 1760/// @code ::new Foo(23, "hello") @endcode 1761/// 1762/// \param StartLoc The first location of the expression. 1763/// \param UseGlobal True if 'new' was prefixed with '::'. 1764/// \param PlacementLParen Opening paren of the placement arguments. 1765/// \param PlacementArgs Placement new arguments. 1766/// \param PlacementRParen Closing paren of the placement arguments. 1767/// \param TypeIdParens If the type is in parens, the source range. 1768/// \param D The type to be allocated, as well as array dimensions. 1769/// \param Initializer The initializing expression or initializer-list, or null 1770/// if there is none. 1771ExprResult 1772Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 1773 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 1774 SourceLocation PlacementRParen, SourceRange TypeIdParens, 1775 Declarator &D, Expr *Initializer) { 1776 Optional<Expr *> ArraySize; 1777 // If the specified type is an array, unwrap it and save the expression. 1778 if (D.getNumTypeObjects() > 0 && 1779 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 1780 DeclaratorChunk &Chunk = D.getTypeObject(0); 1781 if (D.getDeclSpec().hasAutoTypeSpec()) 1782 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) 1783 << D.getSourceRange()); 1784 if (Chunk.Arr.hasStatic) 1785 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 1786 << D.getSourceRange()); 1787 if (!Chunk.Arr.NumElts && !Initializer) 1788 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 1789 << D.getSourceRange()); 1790 1791 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 1792 D.DropFirstTypeObject(); 1793 } 1794 1795 // Every dimension shall be of constant size. 1796 if (ArraySize) { 1797 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 1798 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 1799 break; 1800 1801 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 1802 if (Expr *NumElts = (Expr *)Array.NumElts) { 1803 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { 1804 // FIXME: GCC permits constant folding here. We should either do so consistently 1805 // or not do so at all, rather than changing behavior in C++14 onwards. 1806 if (getLangOpts().CPlusPlus14) { 1807 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator 1808 // shall be a converted constant expression (5.19) of type std::size_t 1809 // and shall evaluate to a strictly positive value. 1810 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); 1811 Array.NumElts 1812 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value, 1813 CCEK_ArrayBound) 1814 .get(); 1815 } else { 1816 Array.NumElts = 1817 VerifyIntegerConstantExpression( 1818 NumElts, nullptr, diag::err_new_array_nonconst, AllowFold) 1819 .get(); 1820 } 1821 if (!Array.NumElts) 1822 return ExprError(); 1823 } 1824 } 1825 } 1826 } 1827 1828 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr); 1829 QualType AllocType = TInfo->getType(); 1830 if (D.isInvalidType()) 1831 return ExprError(); 1832 1833 SourceRange DirectInitRange; 1834 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) 1835 DirectInitRange = List->getSourceRange(); 1836 1837 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal, 1838 PlacementLParen, PlacementArgs, PlacementRParen, 1839 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange, 1840 Initializer); 1841} 1842 1843static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, 1844 Expr *Init) { 1845 if (!Init) 1846 return true; 1847 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) 1848 return PLE->getNumExprs() == 0; 1849 if (isa<ImplicitValueInitExpr>(Init)) 1850 return true; 1851 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) 1852 return !CCE->isListInitialization() && 1853 CCE->getConstructor()->isDefaultConstructor(); 1854 else if (Style == CXXNewExpr::ListInit) { 1855 assert(isa<InitListExpr>(Init) &&(static_cast <bool> (isa<InitListExpr>(Init) &&
"Shouldn't create list CXXConstructExprs for arrays.") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1856, __extension__ __PRETTY_FUNCTION__))
1856 "Shouldn't create list CXXConstructExprs for arrays.")(static_cast <bool> (isa<InitListExpr>(Init) &&
"Shouldn't create list CXXConstructExprs for arrays.") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1856, __extension__ __PRETTY_FUNCTION__))
; 1857 return true; 1858 } 1859 return false; 1860} 1861 1862bool 1863Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { 1864 if (!getLangOpts().AlignedAllocationUnavailable) 1865 return false; 1866 if (FD.isDefined()) 1867 return false; 1868 Optional<unsigned> AlignmentParam; 1869 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) && 1870 AlignmentParam.hasValue()) 1871 return true; 1872 return false; 1873} 1874 1875// Emit a diagnostic if an aligned allocation/deallocation function that is not 1876// implemented in the standard library is selected. 1877void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 1878 SourceLocation Loc) { 1879 if (isUnavailableAlignedAllocationFunction(FD)) { 1880 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); 1881 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( 1882 getASTContext().getTargetInfo().getPlatformName()); 1883 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS()); 1884 1885 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator(); 1886 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete; 1887 Diag(Loc, diag::err_aligned_allocation_unavailable) 1888 << IsDelete << FD.getType().getAsString() << OSName 1889 << OSVersion.getAsString() << OSVersion.empty(); 1890 Diag(Loc, diag::note_silence_aligned_allocation_unavailable); 1891 } 1892} 1893 1894ExprResult 1895Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, 1896 SourceLocation PlacementLParen, 1897 MultiExprArg PlacementArgs, 1898 SourceLocation PlacementRParen, 1899 SourceRange TypeIdParens, 1900 QualType AllocType, 1901 TypeSourceInfo *AllocTypeInfo, 1902 Optional<Expr *> ArraySize, 1903 SourceRange DirectInitRange, 1904 Expr *Initializer) { 1905 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 1906 SourceLocation StartLoc = Range.getBegin(); 1907 1908 CXXNewExpr::InitializationStyle initStyle; 1909 if (DirectInitRange.isValid()) { 1910 assert(Initializer && "Have parens but no initializer.")(static_cast <bool> (Initializer && "Have parens but no initializer."
) ? void (0) : __assert_fail ("Initializer && \"Have parens but no initializer.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1910, __extension__ __PRETTY_FUNCTION__))
; 1911 initStyle = CXXNewExpr::CallInit; 1912 } else if (Initializer && isa<InitListExpr>(Initializer)) 1913 initStyle = CXXNewExpr::ListInit; 1914 else { 1915 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr
>(Initializer) || isa<CXXConstructExpr>(Initializer)
) && "Initializer expression that cannot have been implicitly created."
) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1917, __extension__ __PRETTY_FUNCTION__))
1916 isa<CXXConstructExpr>(Initializer)) &&(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr
>(Initializer) || isa<CXXConstructExpr>(Initializer)
) && "Initializer expression that cannot have been implicitly created."
) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1917, __extension__ __PRETTY_FUNCTION__))
1917 "Initializer expression that cannot have been implicitly created.")(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr
>(Initializer) || isa<CXXConstructExpr>(Initializer)
) && "Initializer expression that cannot have been implicitly created."
) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1917, __extension__ __PRETTY_FUNCTION__))
; 1918 initStyle = CXXNewExpr::NoInit; 1919 } 1920 1921 Expr **Inits = &Initializer; 1922 unsigned NumInits = Initializer ? 1 : 0; 1923 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) { 1924 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init")(static_cast <bool> (initStyle == CXXNewExpr::CallInit &&
"paren init for non-call init") ? void (0) : __assert_fail (
"initStyle == CXXNewExpr::CallInit && \"paren init for non-call init\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 1924, __extension__ __PRETTY_FUNCTION__))
; 1925 Inits = List->getExprs(); 1926 NumInits = List->getNumExprs(); 1927 } 1928 1929 // C++11 [expr.new]p15: 1930 // A new-expression that creates an object of type T initializes that 1931 // object as follows: 1932 InitializationKind Kind 1933 // - If the new-initializer is omitted, the object is default- 1934 // initialized (8.5); if no initialization is performed, 1935 // the object has indeterminate value 1936 = initStyle == CXXNewExpr::NoInit 1937 ? InitializationKind::CreateDefault(TypeRange.getBegin()) 1938 // - Otherwise, the new-initializer is interpreted according to 1939 // the 1940 // initialization rules of 8.5 for direct-initialization. 1941 : initStyle == CXXNewExpr::ListInit 1942 ? InitializationKind::CreateDirectList( 1943 TypeRange.getBegin(), Initializer->getBeginLoc(), 1944 Initializer->getEndLoc()) 1945 : InitializationKind::CreateDirect(TypeRange.getBegin(), 1946 DirectInitRange.getBegin(), 1947 DirectInitRange.getEnd()); 1948 1949 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. 1950 auto *Deduced = AllocType->getContainedDeducedType(); 1951 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { 1952 if (ArraySize) 1953 return ExprError( 1954 Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), 1955 diag::err_deduced_class_template_compound_type) 1956 << /*array*/ 2 1957 << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); 1958 1959 InitializedEntity Entity 1960 = InitializedEntity::InitializeNew(StartLoc, AllocType); 1961 AllocType = DeduceTemplateSpecializationFromInitializer( 1962 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits)); 1963 if (AllocType.isNull()) 1964 return ExprError(); 1965 } else if (Deduced) { 1966 bool Braced = (initStyle == CXXNewExpr::ListInit); 1967 if (NumInits == 1) { 1968 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) { 1969 Inits = p->getInits(); 1970 NumInits = p->getNumInits(); 1971 Braced = true; 1972 } 1973 } 1974 1975 if (initStyle == CXXNewExpr::NoInit || NumInits == 0) 1976 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) 1977 << AllocType << TypeRange); 1978 if (NumInits > 1) { 1979 Expr *FirstBad = Inits[1]; 1980 return ExprError(Diag(FirstBad->getBeginLoc(), 1981 diag::err_auto_new_ctor_multiple_expressions) 1982 << AllocType << TypeRange); 1983 } 1984 if (Braced && !getLangOpts().CPlusPlus17) 1985 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) 1986 << AllocType << TypeRange; 1987 Expr *Deduce = Inits[0]; 1988 QualType DeducedType; 1989 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed) 1990 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 1991 << AllocType << Deduce->getType() 1992 << TypeRange << Deduce->getSourceRange()); 1993 if (DeducedType.isNull()) 1994 return ExprError(); 1995 AllocType = DeducedType; 1996 } 1997 1998 // Per C++0x [expr.new]p5, the type being constructed may be a 1999 // typedef of an array type. 2000 if (!ArraySize) { 2001 if (const ConstantArrayType *Array 2002 = Context.getAsConstantArrayType(AllocType)) { 2003 ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 2004 Context.getSizeType(), 2005 TypeRange.getEnd()); 2006 AllocType = Array->getElementType(); 2007 } 2008 } 2009 2010 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 2011 return ExprError(); 2012 2013 // In ARC, infer 'retaining' for the allocated 2014 if (getLangOpts().ObjCAutoRefCount && 2015 AllocType.getObjCLifetime() == Qualifiers::OCL_None && 2016 AllocType->isObjCLifetimeType()) { 2017 AllocType = Context.getLifetimeQualifiedType(AllocType, 2018 AllocType->getObjCARCImplicitLifetime()); 2019 } 2020 2021 QualType ResultType = Context.getPointerType(AllocType); 2022 2023 if (ArraySize && *ArraySize && 2024 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) { 2025 ExprResult result = CheckPlaceholderExpr(*ArraySize); 2026 if (result.isInvalid()) return ExprError(); 2027 ArraySize = result.get(); 2028 } 2029 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have 2030 // integral or enumeration type with a non-negative value." 2031 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped 2032 // enumeration type, or a class type for which a single non-explicit 2033 // conversion function to integral or unscoped enumeration type exists. 2034 // C++1y [expr.new]p6: The expression [...] is implicitly converted to 2035 // std::size_t. 2036 llvm::Optional<uint64_t> KnownArraySize; 2037 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { 2038 ExprResult ConvertedSize; 2039 if (getLangOpts().CPlusPlus14) { 2040 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?")(static_cast <bool> (Context.getTargetInfo().getIntWidth
() && "Builtin type of size 0?") ? void (0) : __assert_fail
("Context.getTargetInfo().getIntWidth() && \"Builtin type of size 0?\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 2040, __extension__ __PRETTY_FUNCTION__))
; 2041 2042 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(), 2043 AA_Converting); 2044 2045 if (!ConvertedSize.isInvalid() && 2046 (*ArraySize)->getType()->getAs<RecordType>()) 2047 // Diagnose the compatibility of this conversion. 2048 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) 2049 << (*ArraySize)->getType() << 0 << "'size_t'"; 2050 } else { 2051 class SizeConvertDiagnoser : public ICEConvertDiagnoser { 2052 protected: 2053 Expr *ArraySize; 2054 2055 public: 2056 SizeConvertDiagnoser(Expr *ArraySize) 2057 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), 2058 ArraySize(ArraySize) {} 2059 2060 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 2061 QualType T) override { 2062 return S.Diag(Loc, diag::err_array_size_not_integral) 2063 << S.getLangOpts().CPlusPlus11 << T; 2064 } 2065 2066 SemaDiagnosticBuilder diagnoseIncomplete( 2067 Sema &S, SourceLocation Loc, QualType T) override { 2068 return S.Diag(Loc, diag::err_array_size_incomplete_type) 2069 << T << ArraySize->getSourceRange(); 2070 } 2071 2072 SemaDiagnosticBuilder diagnoseExplicitConv( 2073 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 2074 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; 2075 } 2076 2077 SemaDiagnosticBuilder noteExplicitConv( 2078 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 2079 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 2080 << ConvTy->isEnumeralType() << ConvTy; 2081 } 2082 2083 SemaDiagnosticBuilder diagnoseAmbiguous( 2084 Sema &S, SourceLocation Loc, QualType T) override { 2085 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; 2086 } 2087 2088 SemaDiagnosticBuilder noteAmbiguous( 2089 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 2090 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 2091 << ConvTy->isEnumeralType() << ConvTy; 2092 } 2093 2094 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 2095 QualType T, 2096 QualType ConvTy) override { 2097 return S.Diag(Loc, 2098 S.getLangOpts().CPlusPlus11 2099 ? diag::warn_cxx98_compat_array_size_conversion 2100 : diag::ext_array_size_conversion) 2101 << T << ConvTy->isEnumeralType() << ConvTy; 2102 } 2103 } SizeDiagnoser(*ArraySize); 2104 2105 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize, 2106 SizeDiagnoser); 2107 } 2108 if (ConvertedSize.isInvalid()) 2109 return ExprError(); 2110 2111 ArraySize = ConvertedSize.get(); 2112 QualType SizeType = (*ArraySize)->getType(); 2113 2114 if (!SizeType->isIntegralOrUnscopedEnumerationType()) 2115 return ExprError(); 2116 2117 // C++98 [expr.new]p7: 2118 // The expression in a direct-new-declarator shall have integral type 2119 // with a non-negative value. 2120 // 2121 // Let's see if this is a constant < 0. If so, we reject it out of hand, 2122 // per CWG1464. Otherwise, if it's not a constant, we must have an 2123 // unparenthesized array type. 2124 if (!(*ArraySize)->isValueDependent()) { 2125 // We've already performed any required implicit conversion to integer or 2126 // unscoped enumeration type. 2127 // FIXME: Per CWG1464, we are required to check the value prior to 2128 // converting to size_t. This will never find a negative array size in 2129 // C++14 onwards, because Value is always unsigned here! 2130 if (Optional<llvm::APSInt> Value = 2131 (*ArraySize)->getIntegerConstantExpr(Context)) { 2132 if (Value->isSigned() && Value->isNegative()) { 2133 return ExprError(Diag((*ArraySize)->getBeginLoc(), 2134 diag::err_typecheck_negative_array_size) 2135 << (*ArraySize)->getSourceRange()); 2136 } 2137 2138 if (!AllocType->isDependentType()) { 2139 unsigned ActiveSizeBits = ConstantArrayType::getNumAddressingBits( 2140 Context, AllocType, *Value); 2141 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 2142 return ExprError( 2143 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) 2144 << toString(*Value, 10) << (*ArraySize)->getSourceRange()); 2145 } 2146 2147 KnownArraySize = Value->getZExtValue(); 2148 } else if (TypeIdParens.isValid()) { 2149 // Can't have dynamic array size when the type-id is in parentheses. 2150 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) 2151 << (*ArraySize)->getSourceRange() 2152 << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 2153 << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 2154 2155 TypeIdParens = SourceRange(); 2156 } 2157 } 2158 2159 // Note that we do *not* convert the argument in any way. It can 2160 // be signed, larger than size_t, whatever. 2161 } 2162 2163 FunctionDecl *OperatorNew = nullptr; 2164 FunctionDecl *OperatorDelete = nullptr; 2165 unsigned Alignment = 2166 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); 2167 unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); 2168 bool PassAlignment = getLangOpts().AlignedAllocation && 2169 Alignment > NewAlignment; 2170 2171 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both; 2172 if (!AllocType->isDependentType() && 2173 !Expr::hasAnyTypeDependentArguments(PlacementArgs) && 2174 FindAllocationFunctions( 2175 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope, 2176 AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs, 2177 OperatorNew, OperatorDelete)) 2178 return ExprError(); 2179 2180 // If this is an array allocation, compute whether the usual array 2181 // deallocation function for the type has a size_t parameter. 2182 bool UsualArrayDeleteWantsSize = false; 2183 if (ArraySize && !AllocType->isDependentType()) 2184 UsualArrayDeleteWantsSize = 2185 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 2186 2187 SmallVector<Expr *, 8> AllPlaceArgs; 2188 if (OperatorNew) { 2189 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); 2190 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction 2191 : VariadicDoesNotApply; 2192 2193 // We've already converted the placement args, just fill in any default 2194 // arguments. Skip the first parameter because we don't have a corresponding 2195 // argument. Skip the second parameter too if we're passing in the 2196 // alignment; we've already filled it in. 2197 unsigned NumImplicitArgs = PassAlignment ? 2 : 1; 2198 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 2199 NumImplicitArgs, PlacementArgs, AllPlaceArgs, 2200 CallType)) 2201 return ExprError(); 2202 2203 if (!AllPlaceArgs.empty()) 2204 PlacementArgs = AllPlaceArgs; 2205 2206 // We would like to perform some checking on the given `operator new` call, 2207 // but the PlacementArgs does not contain the implicit arguments, 2208 // namely allocation size and maybe allocation alignment, 2209 // so we need to conjure them. 2210 2211 QualType SizeTy = Context.getSizeType(); 2212 unsigned SizeTyWidth = Context.getTypeSize(SizeTy); 2213 2214 llvm::APInt SingleEltSize( 2215 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity()); 2216 2217 // How many bytes do we want to allocate here? 2218 llvm::Optional<llvm::APInt> AllocationSize; 2219 if (!ArraySize.hasValue() && !AllocType->isDependentType()) { 2220 // For non-array operator new, we only want to allocate one element. 2221 AllocationSize = SingleEltSize; 2222 } else if (KnownArraySize.hasValue() && !AllocType->isDependentType()) { 2223 // For array operator new, only deal with static array size case. 2224 bool Overflow; 2225 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) 2226 .umul_ov(SingleEltSize, Overflow); 2227 (void)Overflow; 2228 assert((static_cast <bool> (!Overflow && "Expected that all the overflows would have been handled already."
) ? void (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 2230, __extension__ __PRETTY_FUNCTION__))
2229 !Overflow &&(static_cast <bool> (!Overflow && "Expected that all the overflows would have been handled already."
) ? void (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 2230, __extension__ __PRETTY_FUNCTION__))
2230 "Expected that all the overflows would have been handled already.")(static_cast <bool> (!Overflow && "Expected that all the overflows would have been handled already."
) ? void (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 2230, __extension__ __PRETTY_FUNCTION__))
; 2231 } 2232 2233 IntegerLiteral AllocationSizeLiteral( 2234 Context, 2235 AllocationSize.getValueOr(llvm::APInt::getNullValue(SizeTyWidth)), 2236 SizeTy, SourceLocation()); 2237 // Otherwise, if we failed to constant-fold the allocation size, we'll 2238 // just give up and pass-in something opaque, that isn't a null pointer. 2239 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue, 2240 OK_Ordinary, /*SourceExpr=*/nullptr); 2241 2242 // Let's synthesize the alignment argument in case we will need it. 2243 // Since we *really* want to allocate these on stack, this is slightly ugly 2244 // because there might not be a `std::align_val_t` type. 2245 EnumDecl *StdAlignValT = getStdAlignValT(); 2246 QualType AlignValT = 2247 StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy; 2248 IntegerLiteral AlignmentLiteral( 2249 Context, 2250 llvm::APInt(Context.getTypeSize(SizeTy), 2251 Alignment / Context.getCharWidth()), 2252 SizeTy, SourceLocation()); 2253 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT, 2254 CK_IntegralCast, &AlignmentLiteral, 2255 VK_PRValue, FPOptionsOverride()); 2256 2257 // Adjust placement args by prepending conjured size and alignment exprs. 2258 llvm::SmallVector<Expr *, 8> CallArgs; 2259 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size()); 2260 CallArgs.emplace_back(AllocationSize.hasValue() 2261 ? static_cast<Expr *>(&AllocationSizeLiteral) 2262 : &OpaqueAllocationSize); 2263 if (PassAlignment) 2264 CallArgs.emplace_back(&DesiredAlignment); 2265 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end()); 2266 2267 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs); 2268 2269 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs, 2270 /*IsMemberFunction=*/false, StartLoc, Range, CallType); 2271 2272 // Warn if the type is over-aligned and is being allocated by (unaligned) 2273 // global operator new. 2274 if (PlacementArgs.empty() && !PassAlignment && 2275 (OperatorNew->isImplicit() || 2276 (OperatorNew->getBeginLoc().isValid() && 2277 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) { 2278 if (Alignment > NewAlignment) 2279 Diag(StartLoc, diag::warn_overaligned_type) 2280 << AllocType 2281 << unsigned(Alignment / Context.getCharWidth()) 2282 << unsigned(NewAlignment / Context.getCharWidth()); 2283 } 2284 } 2285 2286 // Array 'new' can't have any initializers except empty parentheses. 2287 // Initializer lists are also allowed, in C++11. Rely on the parser for the 2288 // dialect distinction. 2289 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) { 2290 SourceRange InitRange(Inits[0]->getBeginLoc(), 2291 Inits[NumInits - 1]->getEndLoc()); 2292 Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 2293 return ExprError(); 2294 } 2295 2296 // If we can perform the initialization, and we've not already done so, 2297 // do it now. 2298 if (!AllocType->isDependentType() && 2299 !Expr::hasAnyTypeDependentArguments( 2300 llvm::makeArrayRef(Inits, NumInits))) { 2301 // The type we initialize is the complete type, including the array bound. 2302 QualType InitType; 2303 if (KnownArraySize) 2304 InitType = Context.getConstantArrayType( 2305 AllocType, 2306 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 2307 *KnownArraySize), 2308 *ArraySize, ArrayType::Normal, 0); 2309 else if (ArraySize) 2310 InitType = 2311 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0); 2312 else 2313 InitType = AllocType; 2314 2315 InitializedEntity Entity 2316 = InitializedEntity::InitializeNew(StartLoc, InitType); 2317 InitializationSequence InitSeq(*this, Entity, Kind, 2318 MultiExprArg(Inits, NumInits)); 2319 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 2320 MultiExprArg(Inits, NumInits)); 2321 if (FullInit.isInvalid()) 2322 return ExprError(); 2323 2324 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because 2325 // we don't want the initialized object to be destructed. 2326 // FIXME: We should not create these in the first place. 2327 if (CXXBindTemporaryExpr *Binder = 2328 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) 2329 FullInit = Binder->getSubExpr(); 2330 2331 Initializer = FullInit.get(); 2332 2333 // FIXME: If we have a KnownArraySize, check that the array bound of the 2334 // initializer is no greater than that constant value. 2335 2336 if (ArraySize && !*ArraySize) { 2337 auto *CAT = Context.getAsConstantArrayType(Initializer->getType()); 2338 if (CAT) { 2339 // FIXME: Track that the array size was inferred rather than explicitly 2340 // specified. 2341 ArraySize = IntegerLiteral::Create( 2342 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd()); 2343 } else { 2344 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) 2345 << Initializer->getSourceRange(); 2346 } 2347 } 2348 } 2349 2350 // Mark the new and delete operators as referenced. 2351 if (OperatorNew) { 2352 if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) 2353 return ExprError(); 2354 MarkFunctionReferenced(StartLoc, OperatorNew); 2355 } 2356 if (OperatorDelete) { 2357 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) 2358 return ExprError(); 2359 MarkFunctionReferenced(StartLoc, OperatorDelete); 2360 } 2361 2362 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete, 2363 PassAlignment, UsualArrayDeleteWantsSize, 2364 PlacementArgs, TypeIdParens, ArraySize, initStyle, 2365 Initializer, ResultType, AllocTypeInfo, Range, 2366 DirectInitRange); 2367} 2368 2369/// Checks that a type is suitable as the allocated type 2370/// in a new-expression. 2371bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 2372 SourceRange R) { 2373 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 2374 // abstract class type or array thereof. 2375 if (AllocType->isFunctionType()) 2376 return Diag(Loc, diag::err_bad_new_type) 2377 << AllocType << 0 << R; 2378 else if (AllocType->isReferenceType()) 2379 return Diag(Loc, diag::err_bad_new_type) 2380 << AllocType << 1 << R; 2381 else if (!AllocType->isDependentType() && 2382 RequireCompleteSizedType( 2383 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R)) 2384 return true; 2385 else if (RequireNonAbstractType(Loc, AllocType, 2386 diag::err_allocation_of_abstract_type)) 2387 return true; 2388 else if (AllocType->isVariablyModifiedType()) 2389 return Diag(Loc, diag::err_variably_modified_new_type) 2390 << AllocType; 2391 else if (AllocType.getAddressSpace() != LangAS::Default && 2392 !getLangOpts().OpenCLCPlusPlus) 2393 return Diag(Loc, diag::err_address_space_qualified_new) 2394 << AllocType.getUnqualifiedType() 2395 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); 2396 else if (getLangOpts().ObjCAutoRefCount) { 2397 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { 2398 QualType BaseAllocType = Context.getBaseElementType(AT); 2399 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && 2400 BaseAllocType->isObjCLifetimeType()) 2401 return Diag(Loc, diag::err_arc_new_array_without_ownership) 2402 << BaseAllocType; 2403 } 2404 } 2405 2406 return false; 2407} 2408 2409static bool resolveAllocationOverload( 2410 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, 2411 bool &PassAlignment, FunctionDecl *&Operator, 2412 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { 2413 OverloadCandidateSet Candidates(R.getNameLoc(), 2414 OverloadCandidateSet::CSK_Normal); 2415 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 2416 Alloc != AllocEnd; ++Alloc) { 2417 // Even member operator new/delete are implicitly treated as 2418 // static, so don't use AddMemberCandidate. 2419 NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 2420 2421 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 2422 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 2423 /*ExplicitTemplateArgs=*/nullptr, Args, 2424 Candidates, 2425 /*SuppressUserConversions=*/false); 2426 continue; 2427 } 2428 2429 FunctionDecl *Fn = cast<FunctionDecl>(D); 2430 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, 2431 /*SuppressUserConversions=*/false); 2432 } 2433 2434 // Do the resolution. 2435 OverloadCandidateSet::iterator Best; 2436 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 2437 case OR_Success: { 2438 // Got one! 2439 FunctionDecl *FnDecl = Best->Function; 2440 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), 2441 Best->FoundDecl) == Sema::AR_inaccessible) 2442 return true; 2443 2444 Operator = FnDecl; 2445 return false; 2446 } 2447 2448 case OR_No_Viable_Function: 2449 // C++17 [expr.new]p13: 2450 // If no matching function is found and the allocated object type has 2451 // new-extended alignment, the alignment argument is removed from the 2452 // argument list, and overload resolution is performed again. 2453 if (PassAlignment) { 2454 PassAlignment = false; 2455 AlignArg = Args[1]; 2456 Args.erase(Args.begin() + 1); 2457 return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 2458 Operator, &Candidates, AlignArg, 2459 Diagnose); 2460 } 2461 2462 // MSVC will fall back on trying to find a matching global operator new 2463 // if operator new[] cannot be found. Also, MSVC will leak by not 2464 // generating a call to operator delete or operator delete[], but we 2465 // will not replicate that bug. 2466 // FIXME: Find out how this interacts with the std::align_val_t fallback 2467 // once MSVC implements it. 2468 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && 2469 S.Context.getLangOpts().MSVCCompat) { 2470 R.clear(); 2471 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); 2472 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 2473 // FIXME: This will give bad diagnostics pointing at the wrong functions. 2474 return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 2475 Operator, /*Candidates=*/nullptr, 2476 /*AlignArg=*/nullptr, Diagnose); 2477 } 2478 2479 if (Diagnose) { 2480 // If this is an allocation of the form 'new (p) X' for some object 2481 // pointer p (or an expression that will decay to such a pointer), 2482 // diagnose the missing inclusion of <new>. 2483 if (!R.isClassLookup() && Args.size() == 2 && 2484 (Args[1]->getType()->isObjectPointerType() || 2485 Args[1]->getType()->isArrayType())) { 2486 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new) 2487 << R.getLookupName() << Range; 2488 // Listing the candidates is unlikely to be useful; skip it. 2489 return true; 2490 } 2491 2492 // Finish checking all candidates before we note any. This checking can 2493 // produce additional diagnostics so can't be interleaved with our 2494 // emission of notes. 2495 // 2496 // For an aligned allocation, separately check the aligned and unaligned 2497 // candidates with their respective argument lists. 2498 SmallVector<OverloadCandidate*, 32> Cands; 2499 SmallVector<OverloadCandidate*, 32> AlignedCands; 2500 llvm::SmallVector<Expr*, 4> AlignedArgs; 2501 if (AlignedCandidates) { 2502 auto IsAligned = [](OverloadCandidate &C) { 2503 return C.Function->getNumParams() > 1 && 2504 C.Function->getParamDecl(1)->getType()->isAlignValT(); 2505 }; 2506 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; 2507 2508 AlignedArgs.reserve(Args.size() + 1); 2509 AlignedArgs.push_back(Args[0]); 2510 AlignedArgs.push_back(AlignArg); 2511 AlignedArgs.append(Args.begin() + 1, Args.end()); 2512 AlignedCands = AlignedCandidates->CompleteCandidates( 2513 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned); 2514 2515 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, 2516 R.getNameLoc(), IsUnaligned); 2517 } else { 2518 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, 2519 R.getNameLoc()); 2520 } 2521 2522 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) 2523 << R.getLookupName() << Range; 2524 if (AlignedCandidates) 2525 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "", 2526 R.getNameLoc()); 2527 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc()); 2528 } 2529 return true; 2530 2531 case OR_Ambiguous: 2532 if (Diagnose) { 2533 Candidates.NoteCandidates( 2534 PartialDiagnosticAt(R.getNameLoc(), 2535 S.PDiag(diag::err_ovl_ambiguous_call) 2536 << R.getLookupName() << Range), 2537 S, OCD_AmbiguousCandidates, Args); 2538 } 2539 return true; 2540 2541 case OR_Deleted: { 2542 if (Diagnose) { 2543 Candidates.NoteCandidates( 2544 PartialDiagnosticAt(R.getNameLoc(), 2545 S.PDiag(diag::err_ovl_deleted_call) 2546 << R.getLookupName() << Range), 2547 S, OCD_AllCandidates, Args); 2548 } 2549 return true; 2550 } 2551 } 2552 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 2552)
; 2553} 2554 2555bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 2556 AllocationFunctionScope NewScope, 2557 AllocationFunctionScope DeleteScope, 2558 QualType AllocType, bool IsArray, 2559 bool &PassAlignment, MultiExprArg PlaceArgs, 2560 FunctionDecl *&OperatorNew, 2561 FunctionDecl *&OperatorDelete, 2562 bool Diagnose) { 2563 // --- Choosing an allocation function --- 2564 // C++ 5.3.4p8 - 14 & 18 2565 // 1) If looking in AFS_Global scope for allocation functions, only look in 2566 // the global scope. Else, if AFS_Class, only look in the scope of the 2567 // allocated class. If AFS_Both, look in both. 2568 // 2) If an array size is given, look for operator new[], else look for 2569 // operator new. 2570 // 3) The first argument is always size_t. Append the arguments from the 2571 // placement form. 2572 2573 SmallVector<Expr*, 8> AllocArgs; 2574 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); 2575 2576 // We don't care about the actual value of these arguments. 2577 // FIXME: Should the Sema create the expression and embed it in the syntax 2578 // tree? Or should the consumer just recalculate the value? 2579 // FIXME: Using a dummy value will interact poorly with attribute enable_if. 2580 IntegerLiteral Size(Context, llvm::APInt::getNullValue( 2581 Context.getTargetInfo().getPointerWidth(0)), 2582 Context.getSizeType(), 2583 SourceLocation()); 2584 AllocArgs.push_back(&Size); 2585 2586 QualType AlignValT = Context.VoidTy; 2587 if (PassAlignment) { 2588 DeclareGlobalNewDelete(); 2589 AlignValT = Context.getTypeDeclType(getStdAlignValT()); 2590 } 2591 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); 2592 if (PassAlignment) 2593 AllocArgs.push_back(&Align); 2594 2595 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end()); 2596 2597 // C++ [expr.new]p8: 2598 // If the allocated type is a non-array type, the allocation 2599 // function's name is operator new and the deallocation function's 2600 // name is operator delete. If the allocated type is an array 2601 // type, the allocation function's name is operator new[] and the 2602 // deallocation function's name is operator delete[]. 2603 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 2604 IsArray ? OO_Array_New : OO_New); 2605 2606 QualType AllocElemType = Context.getBaseElementType(AllocType); 2607 2608 // Find the allocation function. 2609 { 2610 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); 2611 2612 // C++1z [expr.new]p9: 2613 // If the new-expression begins with a unary :: operator, the allocation 2614 // function's name is looked up in the global scope. Otherwise, if the 2615 // allocated type is a class type T or array thereof, the allocation 2616 // function's name is looked up in the scope of T. 2617 if (AllocElemType->isRecordType() && NewScope != AFS_Global) 2618 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); 2619 2620 // We can see ambiguity here if the allocation function is found in 2621 // multiple base classes. 2622 if (R.isAmbiguous()) 2623 return true; 2624 2625 // If this lookup fails to find the name, or if the allocated type is not 2626 // a class type, the allocation function's name is looked up in the 2627 // global scope. 2628 if (R.empty()) { 2629 if (NewScope == AFS_Class) 2630 return true; 2631 2632 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 2633 } 2634 2635 if (getLangOpts().OpenCLCPlusPlus && R.empty()) { 2636 if (PlaceArgs.empty()) { 2637 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; 2638 } else { 2639 Diag(StartLoc, diag::err_openclcxx_placement_new); 2640 } 2641 return true; 2642 } 2643 2644 assert(!R.empty() && "implicitly declared allocation functions not found")(static_cast <bool> (!R.empty() && "implicitly declared allocation functions not found"
) ? void (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 2644, __extension__ __PRETTY_FUNCTION__))
; 2645 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")(static_cast <bool> (!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 2645, __extension__ __PRETTY_FUNCTION__))
; 2646 2647 // We do our own custom access checks below. 2648 R.suppressDiagnostics(); 2649 2650 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, 2651 OperatorNew, /*Candidates=*/nullptr, 2652 /*AlignArg=*/nullptr, Diagnose)) 2653 return true; 2654 } 2655 2656 // We don't need an operator delete if we're running under -fno-exceptions. 2657 if (!getLangOpts().Exceptions) { 2658 OperatorDelete = nullptr; 2659 return false; 2660 } 2661 2662 // Note, the name of OperatorNew might have been changed from array to 2663 // non-array by resolveAllocationOverload. 2664 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 2665 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New 2666 ? OO_Array_Delete 2667 : OO_Delete); 2668 2669 // C++ [expr.new]p19: 2670 // 2671 // If the new-expression begins with a unary :: operator, the 2672 // deallocation function's name is looked up in the global 2673 // scope. Otherwise, if the allocated type is a class type T or an 2674 // array thereof, the deallocation function's name is looked up in 2675 // the scope of T. If this lookup fails to find the name, or if 2676 // the allocated type is not a class type or array thereof, the 2677 // deallocation function's name is looked up in the global scope. 2678 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 2679 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) { 2680 auto *RD = 2681 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl()); 2682 LookupQualifiedName(FoundDelete, RD); 2683 } 2684 if (FoundDelete.isAmbiguous()) 2685 return true; // FIXME: clean up expressions? 2686 2687 // Filter out any destroying operator deletes. We can't possibly call such a 2688 // function in this context, because we're handling the case where the object 2689 // was not successfully constructed. 2690 // FIXME: This is not covered by the language rules yet. 2691 { 2692 LookupResult::Filter Filter = FoundDelete.makeFilter(); 2693 while (Filter.hasNext()) { 2694 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl()); 2695 if (FD && FD->isDestroyingOperatorDelete()) 2696 Filter.erase(); 2697 } 2698 Filter.done(); 2699 } 2700 2701 bool FoundGlobalDelete = FoundDelete.empty(); 2702 if (FoundDelete.empty()) { 2703 FoundDelete.clear(LookupOrdinaryName); 2704 2705 if (DeleteScope == AFS_Class) 2706 return true; 2707 2708 DeclareGlobalNewDelete(); 2709 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 2710 } 2711 2712 FoundDelete.suppressDiagnostics(); 2713 2714 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 2715 2716 // Whether we're looking for a placement operator delete is dictated 2717 // by whether we selected a placement operator new, not by whether 2718 // we had explicit placement arguments. This matters for things like 2719 // struct A { void *operator new(size_t, int = 0); ... }; 2720 // A *a = new A() 2721 // 2722 // We don't have any definition for what a "placement allocation function" 2723 // is, but we assume it's any allocation function whose 2724 // parameter-declaration-clause is anything other than (size_t). 2725 // 2726 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? 2727 // This affects whether an exception from the constructor of an overaligned 2728 // type uses the sized or non-sized form of aligned operator delete. 2729 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || 2730 OperatorNew->isVariadic(); 2731 2732 if (isPlacementNew) { 2733 // C++ [expr.new]p20: 2734 // A declaration of a placement deallocation function matches the 2735 // declaration of a placement allocation function if it has the 2736 // same number of parameters and, after parameter transformations 2737 // (8.3.5), all parameter types except the first are 2738 // identical. [...] 2739 // 2740 // To perform this comparison, we compute the function type that 2741 // the deallocation function should have, and use that type both 2742 // for template argument deduction and for comparison purposes. 2743 QualType ExpectedFunctionType; 2744 { 2745 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); 2746 2747 SmallVector<QualType, 4> ArgTypes; 2748 ArgTypes.push_back(Context.VoidPtrTy); 2749 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) 2750 ArgTypes.push_back(Proto->getParamType(I)); 2751 2752 FunctionProtoType::ExtProtoInfo EPI; 2753 // FIXME: This is not part of the standard's rule. 2754 EPI.Variadic = Proto->isVariadic(); 2755 2756 ExpectedFunctionType 2757 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); 2758 } 2759 2760 for (LookupResult::iterator D = FoundDelete.begin(), 2761 DEnd = FoundDelete.end(); 2762 D != DEnd; ++D) { 2763 FunctionDecl *Fn = nullptr; 2764 if (FunctionTemplateDecl *FnTmpl = 2765 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 2766 // Perform template argument deduction to try to match the 2767 // expected function type. 2768 TemplateDeductionInfo Info(StartLoc); 2769 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, 2770 Info)) 2771 continue; 2772 } else 2773 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 2774 2775 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(), 2776 ExpectedFunctionType, 2777 /*AdjustExcpetionSpec*/true), 2778 ExpectedFunctionType)) 2779 Matches.push_back(std::make_pair(D.getPair(), Fn)); 2780 } 2781 2782 if (getLangOpts().CUDA) 2783 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches); 2784 } else { 2785 // C++1y [expr.new]p22: 2786 // For a non-placement allocation function, the normal deallocation 2787 // function lookup is used 2788 // 2789 // Per [expr.delete]p10, this lookup prefers a member operator delete 2790 // without a size_t argument, but prefers a non-member operator delete 2791 // with a size_t where possible (which it always is in this case). 2792 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; 2793 UsualDeallocFnInfo Selected = resolveDeallocationOverload( 2794 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete, 2795 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType), 2796 &BestDeallocFns); 2797 if (Selected) 2798 Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); 2799 else { 2800 // If we failed to select an operator, all remaining functions are viable 2801 // but ambiguous. 2802 for (auto Fn : BestDeallocFns) 2803 Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); 2804 } 2805 } 2806 2807 // C++ [expr.new]p20: 2808 // [...] If the lookup finds a single matching deallocation 2809 // function, that function will be called; otherwise, no 2810 // deallocation function will be called. 2811 if (Matches.size() == 1) { 2812 OperatorDelete = Matches[0].second; 2813 2814 // C++1z [expr.new]p23: 2815 // If the lookup finds a usual deallocation function (3.7.4.2) 2816 // with a parameter of type std::size_t and that function, considered 2817 // as a placement deallocation function, would have been 2818 // selected as a match for the allocation function, the program 2819 // is ill-formed. 2820 if (getLangOpts().CPlusPlus11 && isPlacementNew && 2821 isNonPlacementDeallocationFunction(*this, OperatorDelete)) { 2822 UsualDeallocFnInfo Info(*this, 2823 DeclAccessPair::make(OperatorDelete, AS_public)); 2824 // Core issue, per mail to core reflector, 2016-10-09: 2825 // If this is a member operator delete, and there is a corresponding 2826 // non-sized member operator delete, this isn't /really/ a sized 2827 // deallocation function, it just happens to have a size_t parameter. 2828 bool IsSizedDelete = Info.HasSizeT; 2829 if (IsSizedDelete && !FoundGlobalDelete) { 2830 auto NonSizedDelete = 2831 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false, 2832 /*WantAlign*/Info.HasAlignValT); 2833 if (NonSizedDelete && !NonSizedDelete.HasSizeT && 2834 NonSizedDelete.HasAlignValT == Info.HasAlignValT) 2835 IsSizedDelete = false; 2836 } 2837 2838 if (IsSizedDelete) { 2839 SourceRange R = PlaceArgs.empty() 2840 ? SourceRange() 2841 : SourceRange(PlaceArgs.front()->getBeginLoc(), 2842 PlaceArgs.back()->getEndLoc()); 2843 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; 2844 if (!OperatorDelete->isImplicit()) 2845 Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 2846 << DeleteName; 2847 } 2848 } 2849 2850 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 2851 Matches[0].first); 2852 } else if (!Matches.empty()) { 2853 // We found multiple suitable operators. Per [expr.new]p20, that means we 2854 // call no 'operator delete' function, but we should at least warn the user. 2855 // FIXME: Suppress this warning if the construction cannot throw. 2856 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) 2857 << DeleteName << AllocElemType; 2858 2859 for (auto &Match : Matches) 2860 Diag(Match.second->getLocation(), 2861 diag::note_member_declared_here) << DeleteName; 2862 } 2863 2864 return false; 2865} 2866 2867/// DeclareGlobalNewDelete - Declare the global forms of operator new and 2868/// delete. These are: 2869/// @code 2870/// // C++03: 2871/// void* operator new(std::size_t) throw(std::bad_alloc); 2872/// void* operator new[](std::size_t) throw(std::bad_alloc); 2873/// void operator delete(void *) throw(); 2874/// void operator delete[](void *) throw(); 2875/// // C++11: 2876/// void* operator new(std::size_t); 2877/// void* operator new[](std::size_t); 2878/// void operator delete(void *) noexcept; 2879/// void operator delete[](void *) noexcept; 2880/// // C++1y: 2881/// void* operator new(std::size_t); 2882/// void* operator new[](std::size_t); 2883/// void operator delete(void *) noexcept; 2884/// void operator delete[](void *) noexcept; 2885/// void operator delete(void *, std::size_t) noexcept; 2886/// void operator delete[](void *, std::size_t) noexcept; 2887/// @endcode 2888/// Note that the placement and nothrow forms of new are *not* implicitly 2889/// declared. Their use requires including \<new\>. 2890void Sema::DeclareGlobalNewDelete() { 2891 if (GlobalNewDeleteDeclared) 2892 return; 2893 2894 // The implicitly declared new and delete operators 2895 // are not supported in OpenCL. 2896 if (getLangOpts().OpenCLCPlusPlus) 2897 return; 2898 2899 // C++ [basic.std.dynamic]p2: 2900 // [...] The following allocation and deallocation functions (18.4) are 2901 // implicitly declared in global scope in each translation unit of a 2902 // program 2903 // 2904 // C++03: 2905 // void* operator new(std::size_t) throw(std::bad_alloc); 2906 // void* operator new[](std::size_t) throw(std::bad_alloc); 2907 // void operator delete(void*) throw(); 2908 // void operator delete[](void*) throw(); 2909 // C++11: 2910 // void* operator new(std::size_t); 2911 // void* operator new[](std::size_t); 2912 // void operator delete(void*) noexcept; 2913 // void operator delete[](void*) noexcept; 2914 // C++1y: 2915 // void* operator new(std::size_t); 2916 // void* operator new[](std::size_t); 2917 // void operator delete(void*) noexcept; 2918 // void operator delete[](void*) noexcept; 2919 // void operator delete(void*, std::size_t) noexcept; 2920 // void operator delete[](void*, std::size_t) noexcept; 2921 // 2922 // These implicit declarations introduce only the function names operator 2923 // new, operator new[], operator delete, operator delete[]. 2924 // 2925 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 2926 // "std" or "bad_alloc" as necessary to form the exception specification. 2927 // However, we do not make these implicit declarations visible to name 2928 // lookup. 2929 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { 2930 // The "std::bad_alloc" class has not yet been declared, so build it 2931 // implicitly. 2932 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 2933 getOrCreateStdNamespace(), 2934 SourceLocation(), SourceLocation(), 2935 &PP.getIdentifierTable().get("bad_alloc"), 2936 nullptr); 2937 getStdBadAlloc()->setImplicit(true); 2938 } 2939 if (!StdAlignValT && getLangOpts().AlignedAllocation) { 2940 // The "std::align_val_t" enum class has not yet been declared, so build it 2941 // implicitly. 2942 auto *AlignValT = EnumDecl::Create( 2943 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), 2944 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); 2945 AlignValT->setIntegerType(Context.getSizeType()); 2946 AlignValT->setPromotionType(Context.getSizeType()); 2947 AlignValT->setImplicit(true); 2948 StdAlignValT = AlignValT; 2949 } 2950 2951 GlobalNewDeleteDeclared = true; 2952 2953 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 2954 QualType SizeT = Context.getSizeType(); 2955 2956 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, 2957 QualType Return, QualType Param) { 2958 llvm::SmallVector<QualType, 3> Params; 2959 Params.push_back(Param); 2960 2961 // Create up to four variants of the function (sized/aligned). 2962 bool HasSizedVariant = getLangOpts().SizedDeallocation && 2963 (Kind == OO_Delete || Kind == OO_Array_Delete); 2964 bool HasAlignedVariant = getLangOpts().AlignedAllocation; 2965 2966 int NumSizeVariants = (HasSizedVariant ? 2 : 1); 2967 int NumAlignVariants = (HasAlignedVariant ? 2 : 1); 2968 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { 2969 if (Sized) 2970 Params.push_back(SizeT); 2971 2972 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { 2973 if (Aligned) 2974 Params.push_back(Context.getTypeDeclType(getStdAlignValT())); 2975 2976 DeclareGlobalAllocationFunction( 2977 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); 2978 2979 if (Aligned) 2980 Params.pop_back(); 2981 } 2982 } 2983 }; 2984 2985 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); 2986 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); 2987 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); 2988 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); 2989} 2990 2991/// DeclareGlobalAllocationFunction - Declares a single implicit global 2992/// allocation function if it doesn't already exist. 2993void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 2994 QualType Return, 2995 ArrayRef<QualType> Params) { 2996 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 2997 2998 // Check if this function is already declared. 2999 DeclContext::lookup_result R = GlobalCtx->lookup(Name); 3000 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); 3001 Alloc != AllocEnd; ++Alloc) { 3002 // Only look at non-template functions, as it is the predefined, 3003 // non-templated allocation function we are trying to declare here. 3004 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 3005 if (Func->getNumParams() == Params.size()) { 3006 llvm::SmallVector<QualType, 3> FuncParams; 3007 for (auto *P : Func->parameters()) 3008 FuncParams.push_back( 3009 Context.getCanonicalType(P->getType().getUnqualifiedType())); 3010 if (llvm::makeArrayRef(FuncParams) == Params) { 3011 // Make the function visible to name lookup, even if we found it in 3012 // an unimported module. It either is an implicitly-declared global 3013 // allocation function, or is suppressing that function. 3014 Func->setVisibleDespiteOwningModule(); 3015 return; 3016 } 3017 } 3018 } 3019 } 3020 3021 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( 3022 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 3023 3024 QualType BadAllocType; 3025 bool HasBadAllocExceptionSpec 3026 = (Name.getCXXOverloadedOperator() == OO_New || 3027 Name.getCXXOverloadedOperator() == OO_Array_New); 3028 if (HasBadAllocExceptionSpec) { 3029 if (!getLangOpts().CPlusPlus11) { 3030 BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 3031 assert(StdBadAlloc && "Must have std::bad_alloc declared")(static_cast <bool> (StdBadAlloc && "Must have std::bad_alloc declared"
) ? void (0) : __assert_fail ("StdBadAlloc && \"Must have std::bad_alloc declared\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3031, __extension__ __PRETTY_FUNCTION__))
; 3032 EPI.ExceptionSpec.Type = EST_Dynamic; 3033 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType); 3034 } 3035 } else { 3036 EPI.ExceptionSpec = 3037 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 3038 } 3039 3040 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { 3041 QualType FnType = Context.getFunctionType(Return, Params, EPI); 3042 FunctionDecl *Alloc = FunctionDecl::Create( 3043 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, 3044 FnType, /*TInfo=*/nullptr, SC_None, false, true); 3045 Alloc->setImplicit(); 3046 // Global allocation functions should always be visible. 3047 Alloc->setVisibleDespiteOwningModule(); 3048 3049 Alloc->addAttr(VisibilityAttr::CreateImplicit( 3050 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden 3051 ? VisibilityAttr::Hidden 3052 : VisibilityAttr::Default)); 3053 3054 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; 3055 for (QualType T : Params) { 3056 ParamDecls.push_back(ParmVarDecl::Create( 3057 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, 3058 /*TInfo=*/nullptr, SC_None, nullptr)); 3059 ParamDecls.back()->setImplicit(); 3060 } 3061 Alloc->setParams(ParamDecls); 3062 if (ExtraAttr) 3063 Alloc->addAttr(ExtraAttr); 3064 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc); 3065 Context.getTranslationUnitDecl()->addDecl(Alloc); 3066 IdResolver.tryAddTopLevelDecl(Alloc, Name); 3067 }; 3068 3069 if (!LangOpts.CUDA) 3070 CreateAllocationFunctionDecl(nullptr); 3071 else { 3072 // Host and device get their own declaration so each can be 3073 // defined or re-declared independently. 3074 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); 3075 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); 3076 } 3077} 3078 3079FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, 3080 bool CanProvideSize, 3081 bool Overaligned, 3082 DeclarationName Name) { 3083 DeclareGlobalNewDelete(); 3084 3085 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); 3086 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 3087 3088 // FIXME: It's possible for this to result in ambiguity, through a 3089 // user-declared variadic operator delete or the enable_if attribute. We 3090 // should probably not consider those cases to be usual deallocation 3091 // functions. But for now we just make an arbitrary choice in that case. 3092 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, 3093 Overaligned); 3094 assert(Result.FD && "operator delete missing from global scope?")(static_cast <bool> (Result.FD && "operator delete missing from global scope?"
) ? void (0) : __assert_fail ("Result.FD && \"operator delete missing from global scope?\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3094, __extension__ __PRETTY_FUNCTION__))
; 3095 return Result.FD; 3096} 3097 3098FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, 3099 CXXRecordDecl *RD) { 3100 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete); 3101 3102 FunctionDecl *OperatorDelete = nullptr; 3103 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 3104 return nullptr; 3105 if (OperatorDelete) 3106 return OperatorDelete; 3107 3108 // If there's no class-specific operator delete, look up the global 3109 // non-array delete. 3110 return FindUsualDeallocationFunction( 3111 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), 3112 Name); 3113} 3114 3115bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 3116 DeclarationName Name, 3117 FunctionDecl *&Operator, bool Diagnose) { 3118 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 3119 // Try to find operator delete/operator delete[] in class scope. 3120 LookupQualifiedName(Found, RD); 3121 3122 if (Found.isAmbiguous()) 3123 return true; 3124 3125 Found.suppressDiagnostics(); 3126 3127 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD)); 3128 3129 // C++17 [expr.delete]p10: 3130 // If the deallocation functions have class scope, the one without a 3131 // parameter of type std::size_t is selected. 3132 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; 3133 resolveDeallocationOverload(*this, Found, /*WantSize*/ false, 3134 /*WantAlign*/ Overaligned, &Matches); 3135 3136 // If we could find an overload, use it. 3137 if (Matches.size() == 1) { 3138 Operator = cast<CXXMethodDecl>(Matches[0].FD); 3139 3140 // FIXME: DiagnoseUseOfDecl? 3141 if (Operator->isDeleted()) { 3142 if (Diagnose) { 3143 Diag(StartLoc, diag::err_deleted_function_use); 3144 NoteDeletedFunction(Operator); 3145 } 3146 return true; 3147 } 3148 3149 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 3150 Matches[0].Found, Diagnose) == AR_inaccessible) 3151 return true; 3152 3153 return false; 3154 } 3155 3156 // We found multiple suitable operators; complain about the ambiguity. 3157 // FIXME: The standard doesn't say to do this; it appears that the intent 3158 // is that this should never happen. 3159 if (!Matches.empty()) { 3160 if (Diagnose) { 3161 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 3162 << Name << RD; 3163 for (auto &Match : Matches) 3164 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; 3165 } 3166 return true; 3167 } 3168 3169 // We did find operator delete/operator delete[] declarations, but 3170 // none of them were suitable. 3171 if (!Found.empty()) { 3172 if (Diagnose) { 3173 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 3174 << Name << RD; 3175 3176 for (NamedDecl *D : Found) 3177 Diag(D->getUnderlyingDecl()->getLocation(), 3178 diag::note_member_declared_here) << Name; 3179 } 3180 return true; 3181 } 3182 3183 Operator = nullptr; 3184 return false; 3185} 3186 3187namespace { 3188/// Checks whether delete-expression, and new-expression used for 3189/// initializing deletee have the same array form. 3190class MismatchingNewDeleteDetector { 3191public: 3192 enum MismatchResult { 3193 /// Indicates that there is no mismatch or a mismatch cannot be proven. 3194 NoMismatch, 3195 /// Indicates that variable is initialized with mismatching form of \a new. 3196 VarInitMismatches, 3197 /// Indicates that member is initialized with mismatching form of \a new. 3198 MemberInitMismatches, 3199 /// Indicates that 1 or more constructors' definitions could not been 3200 /// analyzed, and they will be checked again at the end of translation unit. 3201 AnalyzeLater 3202 }; 3203 3204 /// \param EndOfTU True, if this is the final analysis at the end of 3205 /// translation unit. False, if this is the initial analysis at the point 3206 /// delete-expression was encountered. 3207 explicit MismatchingNewDeleteDetector(bool EndOfTU) 3208 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), 3209 HasUndefinedConstructors(false) {} 3210 3211 /// Checks whether pointee of a delete-expression is initialized with 3212 /// matching form of new-expression. 3213 /// 3214 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the 3215 /// point where delete-expression is encountered, then a warning will be 3216 /// issued immediately. If return value is \c AnalyzeLater at the point where 3217 /// delete-expression is seen, then member will be analyzed at the end of 3218 /// translation unit. \c AnalyzeLater is returned iff at least one constructor 3219 /// couldn't be analyzed. If at least one constructor initializes the member 3220 /// with matching type of new, the return value is \c NoMismatch. 3221 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); 3222 /// Analyzes a class member. 3223 /// \param Field Class member to analyze. 3224 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used 3225 /// for deleting the \p Field. 3226 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); 3227 FieldDecl *Field; 3228 /// List of mismatching new-expressions used for initialization of the pointee 3229 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; 3230 /// Indicates whether delete-expression was in array form. 3231 bool IsArrayForm; 3232 3233private: 3234 const bool EndOfTU; 3235 /// Indicates that there is at least one constructor without body. 3236 bool HasUndefinedConstructors; 3237 /// Returns \c CXXNewExpr from given initialization expression. 3238 /// \param E Expression used for initializing pointee in delete-expression. 3239 /// E can be a single-element \c InitListExpr consisting of new-expression. 3240 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); 3241 /// Returns whether member is initialized with mismatching form of 3242 /// \c new either by the member initializer or in-class initialization. 3243 /// 3244 /// If bodies of all constructors are not visible at the end of translation 3245 /// unit or at least one constructor initializes member with the matching 3246 /// form of \c new, mismatch cannot be proven, and this function will return 3247 /// \c NoMismatch. 3248 MismatchResult analyzeMemberExpr(const MemberExpr *ME); 3249 /// Returns whether variable is initialized with mismatching form of 3250 /// \c new. 3251 /// 3252 /// If variable is initialized with matching form of \c new or variable is not 3253 /// initialized with a \c new expression, this function will return true. 3254 /// If variable is initialized with mismatching form of \c new, returns false. 3255 /// \param D Variable to analyze. 3256 bool hasMatchingVarInit(const DeclRefExpr *D); 3257 /// Checks whether the constructor initializes pointee with mismatching 3258 /// form of \c new. 3259 /// 3260 /// Returns true, if member is initialized with matching form of \c new in 3261 /// member initializer list. Returns false, if member is initialized with the 3262 /// matching form of \c new in this constructor's initializer or given 3263 /// constructor isn't defined at the point where delete-expression is seen, or 3264 /// member isn't initialized by the constructor. 3265 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); 3266 /// Checks whether member is initialized with matching form of 3267 /// \c new in member initializer list. 3268 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); 3269 /// Checks whether member is initialized with mismatching form of \c new by 3270 /// in-class initializer. 3271 MismatchResult analyzeInClassInitializer(); 3272}; 3273} 3274 3275MismatchingNewDeleteDetector::MismatchResult 3276MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { 3277 NewExprs.clear(); 3278 assert(DE && "Expected delete-expression")(static_cast <bool> (DE && "Expected delete-expression"
) ? void (0) : __assert_fail ("DE && \"Expected delete-expression\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3278, __extension__ __PRETTY_FUNCTION__))
; 3279 IsArrayForm = DE->isArrayForm(); 3280 const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); 3281 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { 3282 return analyzeMemberExpr(ME); 3283 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { 3284 if (!hasMatchingVarInit(D)) 3285 return VarInitMismatches; 3286 } 3287 return NoMismatch; 3288} 3289 3290const CXXNewExpr * 3291MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { 3292 assert(E != nullptr && "Expected a valid initializer expression")(static_cast <bool> (E != nullptr && "Expected a valid initializer expression"
) ? void (0) : __assert_fail ("E != nullptr && \"Expected a valid initializer expression\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3292, __extension__ __PRETTY_FUNCTION__))
; 3293 E = E->IgnoreParenImpCasts(); 3294 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { 3295 if (ILE->getNumInits() == 1) 3296 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); 3297 } 3298 3299 return dyn_cast_or_null<const CXXNewExpr>(E); 3300} 3301 3302bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( 3303 const CXXCtorInitializer *CI) { 3304 const CXXNewExpr *NE = nullptr; 3305 if (Field == CI->getMember() && 3306 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) { 3307 if (NE->isArray() == IsArrayForm) 3308 return true; 3309 else 3310 NewExprs.push_back(NE); 3311 } 3312 return false; 3313} 3314 3315bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( 3316 const CXXConstructorDecl *CD) { 3317 if (CD->isImplicit()) 3318 return false; 3319 const FunctionDecl *Definition = CD; 3320 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { 3321 HasUndefinedConstructors = true; 3322 return EndOfTU; 3323 } 3324 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { 3325 if (hasMatchingNewInCtorInit(CI)) 3326 return true; 3327 } 3328 return false; 3329} 3330 3331MismatchingNewDeleteDetector::MismatchResult 3332MismatchingNewDeleteDetector::analyzeInClassInitializer() { 3333 assert(Field != nullptr && "This should be called only for members")(static_cast <bool> (Field != nullptr && "This should be called only for members"
) ? void (0) : __assert_fail ("Field != nullptr && \"This should be called only for members\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3333, __extension__ __PRETTY_FUNCTION__))
; 3334 const Expr *InitExpr = Field->getInClassInitializer(); 3335 if (!InitExpr) 3336 return EndOfTU ? NoMismatch : AnalyzeLater; 3337 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { 3338 if (NE->isArray() != IsArrayForm) { 3339 NewExprs.push_back(NE); 3340 return MemberInitMismatches; 3341 } 3342 } 3343 return NoMismatch; 3344} 3345 3346MismatchingNewDeleteDetector::MismatchResult 3347MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, 3348 bool DeleteWasArrayForm) { 3349 assert(Field != nullptr && "Analysis requires a valid class member.")(static_cast <bool> (Field != nullptr && "Analysis requires a valid class member."
) ? void (0) : __assert_fail ("Field != nullptr && \"Analysis requires a valid class member.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3349, __extension__ __PRETTY_FUNCTION__))
; 3350 this->Field = Field; 3351 IsArrayForm = DeleteWasArrayForm; 3352 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); 3353 for (const auto *CD : RD->ctors()) { 3354 if (hasMatchingNewInCtor(CD)) 3355 return NoMismatch; 3356 } 3357 if (HasUndefinedConstructors) 3358 return EndOfTU ? NoMismatch : AnalyzeLater; 3359 if (!NewExprs.empty()) 3360 return MemberInitMismatches; 3361 return Field->hasInClassInitializer() ? analyzeInClassInitializer() 3362 : NoMismatch; 3363} 3364 3365MismatchingNewDeleteDetector::MismatchResult 3366MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { 3367 assert(ME != nullptr && "Expected a member expression")(static_cast <bool> (ME != nullptr && "Expected a member expression"
) ? void (0) : __assert_fail ("ME != nullptr && \"Expected a member expression\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3367, __extension__ __PRETTY_FUNCTION__))
; 3368 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3369 return analyzeField(F, IsArrayForm); 3370 return NoMismatch; 3371} 3372 3373bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { 3374 const CXXNewExpr *NE = nullptr; 3375 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { 3376 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && 3377 NE->isArray() != IsArrayForm) { 3378 NewExprs.push_back(NE); 3379 } 3380 } 3381 return NewExprs.empty(); 3382} 3383 3384static void 3385DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, 3386 const MismatchingNewDeleteDetector &Detector) { 3387 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); 3388 FixItHint H; 3389 if (!Detector.IsArrayForm) 3390 H = FixItHint::CreateInsertion(EndOfDelete, "[]"); 3391 else { 3392 SourceLocation RSquare = Lexer::findLocationAfterToken( 3393 DeleteLoc, tok::l_square, SemaRef.getSourceManager(), 3394 SemaRef.getLangOpts(), true); 3395 if (RSquare.isValid()) 3396 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); 3397 } 3398 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) 3399 << Detector.IsArrayForm << H; 3400 3401 for (const auto *NE : Detector.NewExprs) 3402 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) 3403 << Detector.IsArrayForm; 3404} 3405 3406void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { 3407 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) 3408 return; 3409 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); 3410 switch (Detector.analyzeDeleteExpr(DE)) { 3411 case MismatchingNewDeleteDetector::VarInitMismatches: 3412 case MismatchingNewDeleteDetector::MemberInitMismatches: { 3413 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector); 3414 break; 3415 } 3416 case MismatchingNewDeleteDetector::AnalyzeLater: { 3417 DeleteExprs[Detector.Field].push_back( 3418 std::make_pair(DE->getBeginLoc(), DE->isArrayForm())); 3419 break; 3420 } 3421 case MismatchingNewDeleteDetector::NoMismatch: 3422 break; 3423 } 3424} 3425 3426void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 3427 bool DeleteWasArrayForm) { 3428 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); 3429 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { 3430 case MismatchingNewDeleteDetector::VarInitMismatches: 3431 llvm_unreachable("This analysis should have been done for class members.")::llvm::llvm_unreachable_internal("This analysis should have been done for class members."
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3431)
; 3432 case MismatchingNewDeleteDetector::AnalyzeLater: 3433 llvm_unreachable("Analysis cannot be postponed any point beyond end of "::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3434)
3434 "translation unit.")::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3434)
; 3435 case MismatchingNewDeleteDetector::MemberInitMismatches: 3436 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); 3437 break; 3438 case MismatchingNewDeleteDetector::NoMismatch: 3439 break; 3440 } 3441} 3442 3443/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 3444/// @code ::delete ptr; @endcode 3445/// or 3446/// @code delete [] ptr; @endcode 3447ExprResult 3448Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 3449 bool ArrayForm, Expr *ExE) { 3450 // C++ [expr.delete]p1: 3451 // The operand shall have a pointer type, or a class type having a single 3452 // non-explicit conversion function to a pointer type. The result has type 3453 // void. 3454 // 3455 // DR599 amends "pointer type" to "pointer to object type" in both cases. 3456 3457 ExprResult Ex = ExE; 3458 FunctionDecl *OperatorDelete = nullptr; 3459 bool ArrayFormAsWritten = ArrayForm; 3460 bool UsualArrayDeleteWantsSize = false; 3461 3462 if (!Ex.get()->isTypeDependent()) { 3463 // Perform lvalue-to-rvalue cast, if needed. 3464 Ex = DefaultLvalueConversion(Ex.get()); 3465 if (Ex.isInvalid()) 3466 return ExprError(); 3467 3468 QualType Type = Ex.get()->getType(); 3469 3470 class DeleteConverter : public ContextualImplicitConverter { 3471 public: 3472 DeleteConverter() : ContextualImplicitConverter(false, true) {} 3473 3474 bool match(QualType ConvType) override { 3475 // FIXME: If we have an operator T* and an operator void*, we must pick 3476 // the operator T*. 3477 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 3478 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 3479 return true; 3480 return false; 3481 } 3482 3483 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, 3484 QualType T) override { 3485 return S.Diag(Loc, diag::err_delete_operand) << T; 3486 } 3487 3488 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 3489 QualType T) override { 3490 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; 3491 } 3492 3493 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 3494 QualType T, 3495 QualType ConvTy) override { 3496 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; 3497 } 3498 3499 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 3500 QualType ConvTy) override { 3501 return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 3502 << ConvTy; 3503 } 3504 3505 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 3506 QualType T) override { 3507 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; 3508 } 3509 3510 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 3511 QualType ConvTy) override { 3512 return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 3513 << ConvTy; 3514 } 3515 3516 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 3517 QualType T, 3518 QualType ConvTy) override { 3519 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3519)
; 3520 } 3521 } Converter; 3522 3523 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); 3524 if (Ex.isInvalid()) 3525 return ExprError(); 3526 Type = Ex.get()->getType(); 3527 if (!Converter.match(Type)) 3528 // FIXME: PerformContextualImplicitConversion should return ExprError 3529 // itself in this case. 3530 return ExprError(); 3531 3532 QualType Pointee = Type->castAs<PointerType>()->getPointeeType(); 3533 QualType PointeeElem = Context.getBaseElementType(Pointee); 3534 3535 if (Pointee.getAddressSpace() != LangAS::Default && 3536 !getLangOpts().OpenCLCPlusPlus) 3537 return Diag(Ex.get()->getBeginLoc(), 3538 diag::err_address_space_qualified_delete) 3539 << Pointee.getUnqualifiedType() 3540 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); 3541 3542 CXXRecordDecl *PointeeRD = nullptr; 3543 if (Pointee->isVoidType() && !isSFINAEContext()) { 3544 // The C++ standard bans deleting a pointer to a non-object type, which 3545 // effectively bans deletion of "void*". However, most compilers support 3546 // this, so we treat it as a warning unless we're in a SFINAE context. 3547 Diag(StartLoc, diag::ext_delete_void_ptr_operand) 3548 << Type << Ex.get()->getSourceRange(); 3549 } else if (Pointee->isFunctionType() || Pointee->isVoidType() || 3550 Pointee->isSizelessType()) { 3551 return ExprError(Diag(StartLoc, diag::err_delete_operand) 3552 << Type << Ex.get()->getSourceRange()); 3553 } else if (!Pointee->isDependentType()) { 3554 // FIXME: This can result in errors if the definition was imported from a 3555 // module but is hidden. 3556 if (!RequireCompleteType(StartLoc, Pointee, 3557 diag::warn_delete_incomplete, Ex.get())) { 3558 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) 3559 PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); 3560 } 3561 } 3562 3563 if (Pointee->isArrayType() && !ArrayForm) { 3564 Diag(StartLoc, diag::warn_delete_array_type) 3565 << Type << Ex.get()->getSourceRange() 3566 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); 3567 ArrayForm = true; 3568 } 3569 3570 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 3571 ArrayForm ? OO_Array_Delete : OO_Delete); 3572 3573 if (PointeeRD) { 3574 if (!UseGlobal && 3575 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, 3576 OperatorDelete)) 3577 return ExprError(); 3578 3579 // If we're allocating an array of records, check whether the 3580 // usual operator delete[] has a size_t parameter. 3581 if (ArrayForm) { 3582 // If the user specifically asked to use the global allocator, 3583 // we'll need to do the lookup into the class. 3584 if (UseGlobal) 3585 UsualArrayDeleteWantsSize = 3586 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 3587 3588 // Otherwise, the usual operator delete[] should be the 3589 // function we just found. 3590 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete)) 3591 UsualArrayDeleteWantsSize = 3592 UsualDeallocFnInfo(*this, 3593 DeclAccessPair::make(OperatorDelete, AS_public)) 3594 .HasSizeT; 3595 } 3596 3597 if (!PointeeRD->hasIrrelevantDestructor()) 3598 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 3599 MarkFunctionReferenced(StartLoc, 3600 const_cast<CXXDestructorDecl*>(Dtor)); 3601 if (DiagnoseUseOfDecl(Dtor, StartLoc)) 3602 return ExprError(); 3603 } 3604 3605 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, 3606 /*IsDelete=*/true, /*CallCanBeVirtual=*/true, 3607 /*WarnOnNonAbstractTypes=*/!ArrayForm, 3608 SourceLocation()); 3609 } 3610 3611 if (!OperatorDelete) { 3612 if (getLangOpts().OpenCLCPlusPlus) { 3613 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; 3614 return ExprError(); 3615 } 3616 3617 bool IsComplete = isCompleteType(StartLoc, Pointee); 3618 bool CanProvideSize = 3619 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || 3620 Pointee.isDestructedType()); 3621 bool Overaligned = hasNewExtendedAlignment(*this, Pointee); 3622 3623 // Look for a global declaration. 3624 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, 3625 Overaligned, DeleteName); 3626 } 3627 3628 MarkFunctionReferenced(StartLoc, OperatorDelete); 3629 3630 // Check access and ambiguity of destructor if we're going to call it. 3631 // Note that this is required even for a virtual delete. 3632 bool IsVirtualDelete = false; 3633 if (PointeeRD) { 3634 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 3635 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 3636 PDiag(diag::err_access_dtor) << PointeeElem); 3637 IsVirtualDelete = Dtor->isVirtual(); 3638 } 3639 } 3640 3641 DiagnoseUseOfDecl(OperatorDelete, StartLoc); 3642 3643 // Convert the operand to the type of the first parameter of operator 3644 // delete. This is only necessary if we selected a destroying operator 3645 // delete that we are going to call (non-virtually); converting to void* 3646 // is trivial and left to AST consumers to handle. 3647 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 3648 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { 3649 Qualifiers Qs = Pointee.getQualifiers(); 3650 if (Qs.hasCVRQualifiers()) { 3651 // Qualifiers are irrelevant to this conversion; we're only looking 3652 // for access and ambiguity. 3653 Qs.removeCVRQualifiers(); 3654 QualType Unqual = Context.getPointerType( 3655 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs)); 3656 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp); 3657 } 3658 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing); 3659 if (Ex.isInvalid()) 3660 return ExprError(); 3661 } 3662 } 3663 3664 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( 3665 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, 3666 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); 3667 AnalyzeDeleteExprMismatch(Result); 3668 return Result; 3669} 3670 3671static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, 3672 bool IsDelete, 3673 FunctionDecl *&Operator) { 3674 3675 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( 3676 IsDelete ? OO_Delete : OO_New); 3677 3678 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); 3679 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 3680 assert(!R.empty() && "implicitly declared allocation functions not found")(static_cast <bool> (!R.empty() && "implicitly declared allocation functions not found"
) ? void (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3680, __extension__ __PRETTY_FUNCTION__))
; 3681 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")(static_cast <bool> (!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3681, __extension__ __PRETTY_FUNCTION__))
; 3682 3683 // We do our own custom access checks below. 3684 R.suppressDiagnostics(); 3685 3686 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end()); 3687 OverloadCandidateSet Candidates(R.getNameLoc(), 3688 OverloadCandidateSet::CSK_Normal); 3689 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); 3690 FnOvl != FnOvlEnd; ++FnOvl) { 3691 // Even member operator new/delete are implicitly treated as 3692 // static, so don't use AddMemberCandidate. 3693 NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); 3694 3695 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 3696 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), 3697 /*ExplicitTemplateArgs=*/nullptr, Args, 3698 Candidates, 3699 /*SuppressUserConversions=*/false); 3700 continue; 3701 } 3702 3703 FunctionDecl *Fn = cast<FunctionDecl>(D); 3704 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, 3705 /*SuppressUserConversions=*/false); 3706 } 3707 3708 SourceRange Range = TheCall->getSourceRange(); 3709 3710 // Do the resolution. 3711 OverloadCandidateSet::iterator Best; 3712 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 3713 case OR_Success: { 3714 // Got one! 3715 FunctionDecl *FnDecl = Best->Function; 3716 assert(R.getNamingClass() == nullptr &&(static_cast <bool> (R.getNamingClass() == nullptr &&
"class members should not be considered") ? void (0) : __assert_fail
("R.getNamingClass() == nullptr && \"class members should not be considered\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3717, __extension__ __PRETTY_FUNCTION__))
3717 "class members should not be considered")(static_cast <bool> (R.getNamingClass() == nullptr &&
"class members should not be considered") ? void (0) : __assert_fail
("R.getNamingClass() == nullptr && \"class members should not be considered\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3717, __extension__ __PRETTY_FUNCTION__))
; 3718 3719 if (!FnDecl->isReplaceableGlobalAllocationFunction()) { 3720 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) 3721 << (IsDelete ? 1 : 0) << Range; 3722 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) 3723 << R.getLookupName() << FnDecl->getSourceRange(); 3724 return true; 3725 } 3726 3727 Operator = FnDecl; 3728 return false; 3729 } 3730 3731 case OR_No_Viable_Function: 3732 Candidates.NoteCandidates( 3733 PartialDiagnosticAt(R.getNameLoc(), 3734 S.PDiag(diag::err_ovl_no_viable_function_in_call) 3735 << R.getLookupName() << Range), 3736 S, OCD_AllCandidates, Args); 3737 return true; 3738 3739 case OR_Ambiguous: 3740 Candidates.NoteCandidates( 3741 PartialDiagnosticAt(R.getNameLoc(), 3742 S.PDiag(diag::err_ovl_ambiguous_call) 3743 << R.getLookupName() << Range), 3744 S, OCD_AmbiguousCandidates, Args); 3745 return true; 3746 3747 case OR_Deleted: { 3748 Candidates.NoteCandidates( 3749 PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call) 3750 << R.getLookupName() << Range), 3751 S, OCD_AllCandidates, Args); 3752 return true; 3753 } 3754 } 3755 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3755)
; 3756} 3757 3758ExprResult 3759Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 3760 bool IsDelete) { 3761 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 3762 if (!getLangOpts().CPlusPlus) { 3763 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 3764 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new") 3765 << "C++"; 3766 return ExprError(); 3767 } 3768 // CodeGen assumes it can find the global new and delete to call, 3769 // so ensure that they are declared. 3770 DeclareGlobalNewDelete(); 3771 3772 FunctionDecl *OperatorNewOrDelete = nullptr; 3773 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, 3774 OperatorNewOrDelete)) 3775 return ExprError(); 3776 assert(OperatorNewOrDelete && "should be found")(static_cast <bool> (OperatorNewOrDelete && "should be found"
) ? void (0) : __assert_fail ("OperatorNewOrDelete && \"should be found\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3776, __extension__ __PRETTY_FUNCTION__))
; 3777 3778 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc()); 3779 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete); 3780 3781 TheCall->setType(OperatorNewOrDelete->getReturnType()); 3782 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 3783 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); 3784 InitializedEntity Entity = 3785 InitializedEntity::InitializeParameter(Context, ParamTy, false); 3786 ExprResult Arg = PerformCopyInitialization( 3787 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i)); 3788 if (Arg.isInvalid()) 3789 return ExprError(); 3790 TheCall->setArg(i, Arg.get()); 3791 } 3792 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee()); 3793 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&(static_cast <bool> (Callee && Callee->getCastKind
() == CK_BuiltinFnToFnPtr && "Callee expected to be implicit cast to a builtin function pointer"
) ? void (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3794, __extension__ __PRETTY_FUNCTION__))
3794 "Callee expected to be implicit cast to a builtin function pointer")(static_cast <bool> (Callee && Callee->getCastKind
() == CK_BuiltinFnToFnPtr && "Callee expected to be implicit cast to a builtin function pointer"
) ? void (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3794, __extension__ __PRETTY_FUNCTION__))
; 3795 Callee->setType(OperatorNewOrDelete->getType()); 3796 3797 return TheCallResult; 3798} 3799 3800void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 3801 bool IsDelete, bool CallCanBeVirtual, 3802 bool WarnOnNonAbstractTypes, 3803 SourceLocation DtorLoc) { 3804 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) 3805 return; 3806 3807 // C++ [expr.delete]p3: 3808 // In the first alternative (delete object), if the static type of the 3809 // object to be deleted is different from its dynamic type, the static 3810 // type shall be a base class of the dynamic type of the object to be 3811 // deleted and the static type shall have a virtual destructor or the 3812 // behavior is undefined. 3813 // 3814 const CXXRecordDecl *PointeeRD = dtor->getParent(); 3815 // Note: a final class cannot be derived from, no issue there 3816 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) 3817 return; 3818 3819 // If the superclass is in a system header, there's nothing that can be done. 3820 // The `delete` (where we emit the warning) can be in a system header, 3821 // what matters for this warning is where the deleted type is defined. 3822 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) 3823 return; 3824 3825 QualType ClassType = dtor->getThisType()->getPointeeType(); 3826 if (PointeeRD->isAbstract()) { 3827 // If the class is abstract, we warn by default, because we're 3828 // sure the code has undefined behavior. 3829 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) 3830 << ClassType; 3831 } else if (WarnOnNonAbstractTypes) { 3832 // Otherwise, if this is not an array delete, it's a bit suspect, 3833 // but not necessarily wrong. 3834 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) 3835 << ClassType; 3836 } 3837 if (!IsDelete) { 3838 std::string TypeStr; 3839 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); 3840 Diag(DtorLoc, diag::note_delete_non_virtual) 3841 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); 3842 } 3843} 3844 3845Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, 3846 SourceLocation StmtLoc, 3847 ConditionKind CK) { 3848 ExprResult E = 3849 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); 3850 if (E.isInvalid()) 3851 return ConditionError(); 3852 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc), 3853 CK == ConditionKind::ConstexprIf); 3854} 3855 3856/// Check the use of the given variable as a C++ condition in an if, 3857/// while, do-while, or switch statement. 3858ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 3859 SourceLocation StmtLoc, 3860 ConditionKind CK) { 3861 if (ConditionVar->isInvalidDecl()) 3862 return ExprError(); 3863 3864 QualType T = ConditionVar->getType(); 3865 3866 // C++ [stmt.select]p2: 3867 // The declarator shall not specify a function or an array. 3868 if (T->isFunctionType()) 3869 return ExprError(Diag(ConditionVar->getLocation(), 3870 diag::err_invalid_use_of_function_type) 3871 << ConditionVar->getSourceRange()); 3872 else if (T->isArrayType()) 3873 return ExprError(Diag(ConditionVar->getLocation(), 3874 diag::err_invalid_use_of_array_type) 3875 << ConditionVar->getSourceRange()); 3876 3877 ExprResult Condition = BuildDeclRefExpr( 3878 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, 3879 ConditionVar->getLocation()); 3880 3881 switch (CK) { 3882 case ConditionKind::Boolean: 3883 return CheckBooleanCondition(StmtLoc, Condition.get()); 3884 3885 case ConditionKind::ConstexprIf: 3886 return CheckBooleanCondition(StmtLoc, Condition.get(), true); 3887 3888 case ConditionKind::Switch: 3889 return CheckSwitchCondition(StmtLoc, Condition.get()); 3890 } 3891 3892 llvm_unreachable("unexpected condition kind")::llvm::llvm_unreachable_internal("unexpected condition kind"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3892)
; 3893} 3894 3895/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 3896ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { 3897 // C++ 6.4p4: 3898 // The value of a condition that is an initialized declaration in a statement 3899 // other than a switch statement is the value of the declared variable 3900 // implicitly converted to type bool. If that conversion is ill-formed, the 3901 // program is ill-formed. 3902 // The value of a condition that is an expression is the value of the 3903 // expression, implicitly converted to bool. 3904 // 3905 // FIXME: Return this value to the caller so they don't need to recompute it. 3906 llvm::APSInt Value(/*BitWidth*/1); 3907 return (IsConstexpr && !CondExpr->isValueDependent()) 3908 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value, 3909 CCEK_ConstexprIf) 3910 : PerformContextuallyConvertToBool(CondExpr); 3911} 3912 3913/// Helper function to determine whether this is the (deprecated) C++ 3914/// conversion from a string literal to a pointer to non-const char or 3915/// non-const wchar_t (for narrow and wide string literals, 3916/// respectively). 3917bool 3918Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 3919 // Look inside the implicit cast, if it exists. 3920 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 3921 From = Cast->getSubExpr(); 3922 3923 // A string literal (2.13.4) that is not a wide string literal can 3924 // be converted to an rvalue of type "pointer to char"; a wide 3925 // string literal can be converted to an rvalue of type "pointer 3926 // to wchar_t" (C++ 4.2p2). 3927 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 3928 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 3929 if (const BuiltinType *ToPointeeType 3930 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 3931 // This conversion is considered only when there is an 3932 // explicit appropriate pointer target type (C++ 4.2p2). 3933 if (!ToPtrType->getPointeeType().hasQualifiers()) { 3934 switch (StrLit->getKind()) { 3935 case StringLiteral::UTF8: 3936 case StringLiteral::UTF16: 3937 case StringLiteral::UTF32: 3938 // We don't allow UTF literals to be implicitly converted 3939 break; 3940 case StringLiteral::Ascii: 3941 return (ToPointeeType->getKind() == BuiltinType::Char_U || 3942 ToPointeeType->getKind() == BuiltinType::Char_S); 3943 case StringLiteral::Wide: 3944 return Context.typesAreCompatible(Context.getWideCharType(), 3945 QualType(ToPointeeType, 0)); 3946 } 3947 } 3948 } 3949 3950 return false; 3951} 3952 3953static ExprResult BuildCXXCastArgument(Sema &S, 3954 SourceLocation CastLoc, 3955 QualType Ty, 3956 CastKind Kind, 3957 CXXMethodDecl *Method, 3958 DeclAccessPair FoundDecl, 3959 bool HadMultipleCandidates, 3960 Expr *From) { 3961 switch (Kind) { 3962 default: llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3962)
; 3963 case CK_ConstructorConversion: { 3964 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); 3965 SmallVector<Expr*, 8> ConstructorArgs; 3966 3967 if (S.RequireNonAbstractType(CastLoc, Ty, 3968 diag::err_allocation_of_abstract_type)) 3969 return ExprError(); 3970 3971 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc, 3972 ConstructorArgs)) 3973 return ExprError(); 3974 3975 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, 3976 InitializedEntity::InitializeTemporary(Ty)); 3977 if (S.DiagnoseUseOfDecl(Method, CastLoc)) 3978 return ExprError(); 3979 3980 ExprResult Result = S.BuildCXXConstructExpr( 3981 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), 3982 ConstructorArgs, HadMultipleCandidates, 3983 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 3984 CXXConstructExpr::CK_Complete, SourceRange()); 3985 if (Result.isInvalid()) 3986 return ExprError(); 3987 3988 return S.MaybeBindToTemporary(Result.getAs<Expr>()); 3989 } 3990 3991 case CK_UserDefinedConversion: { 3992 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!")(static_cast <bool> (!From->getType()->isPointerType
() && "Arg can't have pointer type!") ? void (0) : __assert_fail
("!From->getType()->isPointerType() && \"Arg can't have pointer type!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 3992, __extension__ __PRETTY_FUNCTION__))
; 3993 3994 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); 3995 if (S.DiagnoseUseOfDecl(Method, CastLoc)) 3996 return ExprError(); 3997 3998 // Create an implicit call expr that calls it. 3999 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); 4000 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, 4001 HadMultipleCandidates); 4002 if (Result.isInvalid()) 4003 return ExprError(); 4004 // Record usage of conversion in an implicit cast. 4005 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), 4006 CK_UserDefinedConversion, Result.get(), 4007 nullptr, Result.get()->getValueKind(), 4008 S.CurFPFeatureOverrides()); 4009 4010 return S.MaybeBindToTemporary(Result.get()); 4011 } 4012 } 4013} 4014 4015/// PerformImplicitConversion - Perform an implicit conversion of the 4016/// expression From to the type ToType using the pre-computed implicit 4017/// conversion sequence ICS. Returns the converted 4018/// expression. Action is the kind of conversion we're performing, 4019/// used in the error message. 4020ExprResult 4021Sema::PerformImplicitConversion(Expr *From, QualType ToType, 4022 const ImplicitConversionSequence &ICS, 4023 AssignmentAction Action, 4024 CheckedConversionKind CCK) { 4025 // C++ [over.match.oper]p7: [...] operands of class type are converted [...] 4026 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType()) 4027 return From; 4028 4029 switch (ICS.getKind()) { 4030 case ImplicitConversionSequence::StandardConversion: { 4031 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, 4032 Action, CCK); 4033 if (Res.isInvalid()) 4034 return ExprError(); 4035 From = Res.get(); 4036 break; 4037 } 4038 4039 case ImplicitConversionSequence::UserDefinedConversion: { 4040 4041 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 4042 CastKind CastKind; 4043 QualType BeforeToType; 4044 assert(FD && "no conversion function for user-defined conversion seq")(static_cast <bool> (FD && "no conversion function for user-defined conversion seq"
) ? void (0) : __assert_fail ("FD && \"no conversion function for user-defined conversion seq\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4044, __extension__ __PRETTY_FUNCTION__))
; 4045 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 4046 CastKind = CK_UserDefinedConversion; 4047 4048 // If the user-defined conversion is specified by a conversion function, 4049 // the initial standard conversion sequence converts the source type to 4050 // the implicit object parameter of the conversion function. 4051 BeforeToType = Context.getTagDeclType(Conv->getParent()); 4052 } else { 4053 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 4054 CastKind = CK_ConstructorConversion; 4055 // Do no conversion if dealing with ... for the first conversion. 4056 if (!ICS.UserDefined.EllipsisConversion) { 4057 // If the user-defined conversion is specified by a constructor, the 4058 // initial standard conversion sequence converts the source type to 4059 // the type required by the argument of the constructor 4060 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 4061 } 4062 } 4063 // Watch out for ellipsis conversion. 4064 if (!ICS.UserDefined.EllipsisConversion) { 4065 ExprResult Res = 4066 PerformImplicitConversion(From, BeforeToType, 4067 ICS.UserDefined.Before, AA_Converting, 4068 CCK); 4069 if (Res.isInvalid()) 4070 return ExprError(); 4071 From = Res.get(); 4072 } 4073 4074 ExprResult CastArg = BuildCXXCastArgument( 4075 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, 4076 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction, 4077 ICS.UserDefined.HadMultipleCandidates, From); 4078 4079 if (CastArg.isInvalid()) 4080 return ExprError(); 4081 4082 From = CastArg.get(); 4083 4084 // C++ [over.match.oper]p7: 4085 // [...] the second standard conversion sequence of a user-defined 4086 // conversion sequence is not applied. 4087 if (CCK == CCK_ForBuiltinOverloadedOp) 4088 return From; 4089 4090 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 4091 AA_Converting, CCK); 4092 } 4093 4094 case ImplicitConversionSequence::AmbiguousConversion: 4095 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 4096 PDiag(diag::err_typecheck_ambiguous_condition) 4097 << From->getSourceRange()); 4098 return ExprError(); 4099 4100 case ImplicitConversionSequence::EllipsisConversion: 4101 llvm_unreachable("Cannot perform an ellipsis conversion")::llvm::llvm_unreachable_internal("Cannot perform an ellipsis conversion"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4101)
; 4102 4103 case ImplicitConversionSequence::BadConversion: 4104 Sema::AssignConvertType ConvTy = 4105 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType()); 4106 bool Diagnosed = DiagnoseAssignmentResult( 4107 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(), 4108 ToType, From->getType(), From, Action); 4109 assert(Diagnosed && "failed to diagnose bad conversion")(static_cast <bool> (Diagnosed && "failed to diagnose bad conversion"
) ? void (0) : __assert_fail ("Diagnosed && \"failed to diagnose bad conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4109, __extension__ __PRETTY_FUNCTION__))
; (void)Diagnosed; 4110 return ExprError(); 4111 } 4112 4113 // Everything went well. 4114 return From; 4115} 4116 4117/// PerformImplicitConversion - Perform an implicit conversion of the 4118/// expression From to the type ToType by following the standard 4119/// conversion sequence SCS. Returns the converted 4120/// expression. Flavor is the context in which we're performing this 4121/// conversion, for use in error messages. 4122ExprResult 4123Sema::PerformImplicitConversion(Expr *From, QualType ToType, 4124 const StandardConversionSequence& SCS, 4125 AssignmentAction Action, 4126 CheckedConversionKind CCK) { 4127 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); 4128 4129 // Overall FIXME: we are recomputing too many types here and doing far too 4130 // much extra work. What this means is that we need to keep track of more 4131 // information that is computed when we try the implicit conversion initially, 4132 // so that we don't need to recompute anything here. 4133 QualType FromType = From->getType(); 4134 4135 if (SCS.CopyConstructor) { 4136 // FIXME: When can ToType be a reference type? 4137 assert(!ToType->isReferenceType())(static_cast <bool> (!ToType->isReferenceType()) ? void
(0) : __assert_fail ("!ToType->isReferenceType()", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4137, __extension__ __PRETTY_FUNCTION__))
; 4138 if (SCS.Second == ICK_Derived_To_Base) { 4139 SmallVector<Expr*, 8> ConstructorArgs; 4140 if (CompleteConstructorCall( 4141 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From, 4142 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs)) 4143 return ExprError(); 4144 return BuildCXXConstructExpr( 4145 /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 4146 SCS.FoundCopyConstructor, SCS.CopyConstructor, 4147 ConstructorArgs, /*HadMultipleCandidates*/ false, 4148 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 4149 CXXConstructExpr::CK_Complete, SourceRange()); 4150 } 4151 return BuildCXXConstructExpr( 4152 /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 4153 SCS.FoundCopyConstructor, SCS.CopyConstructor, 4154 From, /*HadMultipleCandidates*/ false, 4155 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 4156 CXXConstructExpr::CK_Complete, SourceRange()); 4157 } 4158 4159 // Resolve overloaded function references. 4160 if (Context.hasSameType(FromType, Context.OverloadTy)) { 4161 DeclAccessPair Found; 4162 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 4163 true, Found); 4164 if (!Fn) 4165 return ExprError(); 4166 4167 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) 4168 return ExprError(); 4169 4170 From = FixOverloadedFunctionReference(From, Found, Fn); 4171 FromType = From->getType(); 4172 } 4173 4174 // If we're converting to an atomic type, first convert to the corresponding 4175 // non-atomic type. 4176 QualType ToAtomicType; 4177 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { 4178 ToAtomicType = ToType; 4179 ToType = ToAtomic->getValueType(); 4180 } 4181 4182 QualType InitialFromType = FromType; 4183 // Perform the first implicit conversion. 4184 switch (SCS.First) { 4185 case ICK_Identity: 4186 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { 4187 FromType = FromAtomic->getValueType().getUnqualifiedType(); 4188 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, 4189 From, /*BasePath=*/nullptr, VK_PRValue, 4190 FPOptionsOverride()); 4191 } 4192 break; 4193 4194 case ICK_Lvalue_To_Rvalue: { 4195 assert(From->getObjectKind() != OK_ObjCProperty)(static_cast <bool> (From->getObjectKind() != OK_ObjCProperty
) ? void (0) : __assert_fail ("From->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4195, __extension__ __PRETTY_FUNCTION__))
; 4196 ExprResult FromRes = DefaultLvalueConversion(From); 4197 if (FromRes.isInvalid()) 4198 return ExprError(); 4199 4200 From = FromRes.get(); 4201 FromType = From->getType(); 4202 break; 4203 } 4204 4205 case ICK_Array_To_Pointer: 4206 FromType = Context.getArrayDecayedType(FromType); 4207 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue, 4208 /*BasePath=*/nullptr, CCK) 4209 .get(); 4210 break; 4211 4212 case ICK_Function_To_Pointer: 4213 FromType = Context.getPointerType(FromType); 4214 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 4215 VK_PRValue, /*BasePath=*/nullptr, CCK) 4216 .get(); 4217 break; 4218 4219 default: 4220 llvm_unreachable("Improper first standard conversion")::llvm::llvm_unreachable_internal("Improper first standard conversion"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4220)
; 4221 } 4222 4223 // Perform the second implicit conversion 4224 switch (SCS.Second) { 4225 case ICK_Identity: 4226 // C++ [except.spec]p5: 4227 // [For] assignment to and initialization of pointers to functions, 4228 // pointers to member functions, and references to functions: the 4229 // target entity shall allow at least the exceptions allowed by the 4230 // source value in the assignment or initialization. 4231 switch (Action) { 4232 case AA_Assigning: 4233 case AA_Initializing: 4234 // Note, function argument passing and returning are initialization. 4235 case AA_Passing: 4236 case AA_Returning: 4237 case AA_Sending: 4238 case AA_Passing_CFAudited: 4239 if (CheckExceptionSpecCompatibility(From, ToType)) 4240 return ExprError(); 4241 break; 4242 4243 case AA_Casting: 4244 case AA_Converting: 4245 // Casts and implicit conversions are not initialization, so are not 4246 // checked for exception specification mismatches. 4247 break; 4248 } 4249 // Nothing else to do. 4250 break; 4251 4252 case ICK_Integral_Promotion: 4253 case ICK_Integral_Conversion: 4254 if (ToType->isBooleanType()) { 4255 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&(static_cast <bool> (FromType->castAs<EnumType>
()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion
&& "only enums with fixed underlying type can promote to bool"
) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4257, __extension__ __PRETTY_FUNCTION__))
4256 SCS.Second == ICK_Integral_Promotion &&(static_cast <bool> (FromType->castAs<EnumType>
()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion
&& "only enums with fixed underlying type can promote to bool"
) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4257, __extension__ __PRETTY_FUNCTION__))
4257 "only enums with fixed underlying type can promote to bool")(static_cast <bool> (FromType->castAs<EnumType>
()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion
&& "only enums with fixed underlying type can promote to bool"
) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4257, __extension__ __PRETTY_FUNCTION__))
; 4258 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue, 4259 /*BasePath=*/nullptr, CCK) 4260 .get(); 4261 } else { 4262 From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue, 4263 /*BasePath=*/nullptr, CCK) 4264 .get(); 4265 } 4266 break; 4267 4268 case ICK_Floating_Promotion: 4269 case ICK_Floating_Conversion: 4270 From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue, 4271 /*BasePath=*/nullptr, CCK) 4272 .get(); 4273 break; 4274 4275 case ICK_Complex_Promotion: 4276 case ICK_Complex_Conversion: { 4277 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType(); 4278 QualType ToEl = ToType->castAs<ComplexType>()->getElementType(); 4279 CastKind CK; 4280 if (FromEl->isRealFloatingType()) { 4281 if (ToEl->isRealFloatingType()) 4282 CK = CK_FloatingComplexCast; 4283 else 4284 CK = CK_FloatingComplexToIntegralComplex; 4285 } else if (ToEl->isRealFloatingType()) { 4286 CK = CK_IntegralComplexToFloatingComplex; 4287 } else { 4288 CK = CK_IntegralComplexCast; 4289 } 4290 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr, 4291 CCK) 4292 .get(); 4293 break; 4294 } 4295 4296 case ICK_Floating_Integral: 4297 if (ToType->isRealFloatingType()) 4298 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue, 4299 /*BasePath=*/nullptr, CCK) 4300 .get(); 4301 else 4302 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue, 4303 /*BasePath=*/nullptr, CCK) 4304 .get(); 4305 break; 4306 4307 case ICK_Compatible_Conversion: 4308 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(), 4309 /*BasePath=*/nullptr, CCK).get(); 4310 break; 4311 4312 case ICK_Writeback_Conversion: 4313 case ICK_Pointer_Conversion: { 4314 if (SCS.IncompatibleObjC && Action != AA_Casting) { 4315 // Diagnose incompatible Objective-C conversions 4316 if (Action == AA_Initializing || Action == AA_Assigning) 4317 Diag(From->getBeginLoc(), 4318 diag::ext_typecheck_convert_incompatible_pointer) 4319 << ToType << From->getType() << Action << From->getSourceRange() 4320 << 0; 4321 else 4322 Diag(From->getBeginLoc(), 4323 diag::ext_typecheck_convert_incompatible_pointer) 4324 << From->getType() << ToType << Action << From->getSourceRange() 4325 << 0; 4326 4327 if (From->getType()->isObjCObjectPointerType() && 4328 ToType->isObjCObjectPointerType()) 4329 EmitRelatedResultTypeNote(From); 4330 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 4331 !CheckObjCARCUnavailableWeakConversion(ToType, 4332 From->getType())) { 4333 if (Action == AA_Initializing) 4334 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); 4335 else 4336 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) 4337 << (Action == AA_Casting) << From->getType() << ToType 4338 << From->getSourceRange(); 4339 } 4340 4341 // Defer address space conversion to the third conversion. 4342 QualType FromPteeType = From->getType()->getPointeeType(); 4343 QualType ToPteeType = ToType->getPointeeType(); 4344 QualType NewToType = ToType; 4345 if (!FromPteeType.isNull() && !ToPteeType.isNull() && 4346 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) { 4347 NewToType = Context.removeAddrSpaceQualType(ToPteeType); 4348 NewToType = Context.getAddrSpaceQualType(NewToType, 4349 FromPteeType.getAddressSpace()); 4350 if (ToType->isObjCObjectPointerType()) 4351 NewToType = Context.getObjCObjectPointerType(NewToType); 4352 else if (ToType->isBlockPointerType()) 4353 NewToType = Context.getBlockPointerType(NewToType); 4354 else 4355 NewToType = Context.getPointerType(NewToType); 4356 } 4357 4358 CastKind Kind; 4359 CXXCastPath BasePath; 4360 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle)) 4361 return ExprError(); 4362 4363 // Make sure we extend blocks if necessary. 4364 // FIXME: doing this here is really ugly. 4365 if (Kind == CK_BlockPointerToObjCPointerCast) { 4366 ExprResult E = From; 4367 (void) PrepareCastToObjCObjectPointer(E); 4368 From = E.get(); 4369 } 4370 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 4371 CheckObjCConversion(SourceRange(), NewToType, From, CCK); 4372 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK) 4373 .get(); 4374 break; 4375 } 4376 4377 case ICK_Pointer_Member: { 4378 CastKind Kind; 4379 CXXCastPath BasePath; 4380 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 4381 return ExprError(); 4382 if (CheckExceptionSpecCompatibility(From, ToType)) 4383 return ExprError(); 4384 4385 // We may not have been able to figure out what this member pointer resolved 4386 // to up until this exact point. Attempt to lock-in it's inheritance model. 4387 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4388 (void)isCompleteType(From->getExprLoc(), From->getType()); 4389 (void)isCompleteType(From->getExprLoc(), ToType); 4390 } 4391 4392 From = 4393 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get(); 4394 break; 4395 } 4396 4397 case ICK_Boolean_Conversion: 4398 // Perform half-to-boolean conversion via float. 4399 if (From->getType()->isHalfType()) { 4400 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); 4401 FromType = Context.FloatTy; 4402 } 4403 4404 From = ImpCastExprToType(From, Context.BoolTy, 4405 ScalarTypeToBooleanCastKind(FromType), VK_PRValue, 4406 /*BasePath=*/nullptr, CCK) 4407 .get(); 4408 break; 4409 4410 case ICK_Derived_To_Base: { 4411 CXXCastPath BasePath; 4412 if (CheckDerivedToBaseConversion( 4413 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), 4414 From->getSourceRange(), &BasePath, CStyle)) 4415 return ExprError(); 4416 4417 From = ImpCastExprToType(From, ToType.getNonReferenceType(), 4418 CK_DerivedToBase, From->getValueKind(), 4419 &BasePath, CCK).get(); 4420 break; 4421 } 4422 4423 case ICK_Vector_Conversion: 4424 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue, 4425 /*BasePath=*/nullptr, CCK) 4426 .get(); 4427 break; 4428 4429 case ICK_SVE_Vector_Conversion: 4430 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue, 4431 /*BasePath=*/nullptr, CCK) 4432 .get(); 4433 break; 4434 4435 case ICK_Vector_Splat: { 4436 // Vector splat from any arithmetic type to a vector. 4437 Expr *Elem = prepareVectorSplat(ToType, From).get(); 4438 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue, 4439 /*BasePath=*/nullptr, CCK) 4440 .get(); 4441 break; 4442 } 4443 4444 case ICK_Complex_Real: 4445 // Case 1. x -> _Complex y 4446 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 4447 QualType ElType = ToComplex->getElementType(); 4448 bool isFloatingComplex = ElType->isRealFloatingType(); 4449 4450 // x -> y 4451 if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 4452 // do nothing 4453 } else if (From->getType()->isRealFloatingType()) { 4454 From = ImpCastExprToType(From, ElType, 4455 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); 4456 } else { 4457 assert(From->getType()->isIntegerType())(static_cast <bool> (From->getType()->isIntegerType
()) ? void (0) : __assert_fail ("From->getType()->isIntegerType()"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4457, __extension__ __PRETTY_FUNCTION__))
; 4458 From = ImpCastExprToType(From, ElType, 4459 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); 4460 } 4461 // y -> _Complex y 4462 From = ImpCastExprToType(From, ToType, 4463 isFloatingComplex ? CK_FloatingRealToComplex 4464 : CK_IntegralRealToComplex).get(); 4465 4466 // Case 2. _Complex x -> y 4467 } else { 4468 auto *FromComplex = From->getType()->castAs<ComplexType>(); 4469 QualType ElType = FromComplex->getElementType(); 4470 bool isFloatingComplex = ElType->isRealFloatingType(); 4471 4472 // _Complex x -> x 4473 From = ImpCastExprToType(From, ElType, 4474 isFloatingComplex ? CK_FloatingComplexToReal 4475 : CK_IntegralComplexToReal, 4476 VK_PRValue, /*BasePath=*/nullptr, CCK) 4477 .get(); 4478 4479 // x -> y 4480 if (Context.hasSameUnqualifiedType(ElType, ToType)) { 4481 // do nothing 4482 } else if (ToType->isRealFloatingType()) { 4483 From = ImpCastExprToType(From, ToType, 4484 isFloatingComplex ? CK_FloatingCast 4485 : CK_IntegralToFloating, 4486 VK_PRValue, /*BasePath=*/nullptr, CCK) 4487 .get(); 4488 } else { 4489 assert(ToType->isIntegerType())(static_cast <bool> (ToType->isIntegerType()) ? void
(0) : __assert_fail ("ToType->isIntegerType()", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4489, __extension__ __PRETTY_FUNCTION__))
; 4490 From = ImpCastExprToType(From, ToType, 4491 isFloatingComplex ? CK_FloatingToIntegral 4492 : CK_IntegralCast, 4493 VK_PRValue, /*BasePath=*/nullptr, CCK) 4494 .get(); 4495 } 4496 } 4497 break; 4498 4499 case ICK_Block_Pointer_Conversion: { 4500 LangAS AddrSpaceL = 4501 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 4502 LangAS AddrSpaceR = 4503 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 4504 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&(static_cast <bool> (Qualifiers::isAddressSpaceSupersetOf
(AddrSpaceL, AddrSpaceR) && "Invalid cast") ? void (0
) : __assert_fail ("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4505, __extension__ __PRETTY_FUNCTION__))
4505 "Invalid cast")(static_cast <bool> (Qualifiers::isAddressSpaceSupersetOf
(AddrSpaceL, AddrSpaceR) && "Invalid cast") ? void (0
) : __assert_fail ("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4505, __extension__ __PRETTY_FUNCTION__))
; 4506 CastKind Kind = 4507 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 4508 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind, 4509 VK_PRValue, /*BasePath=*/nullptr, CCK) 4510 .get(); 4511 break; 4512 } 4513 4514 case ICK_TransparentUnionConversion: { 4515 ExprResult FromRes = From; 4516 Sema::AssignConvertType ConvTy = 4517 CheckTransparentUnionArgumentConstraints(ToType, FromRes); 4518 if (FromRes.isInvalid()) 4519 return ExprError(); 4520 From = FromRes.get(); 4521 assert ((ConvTy == Sema::Compatible) &&(static_cast <bool> ((ConvTy == Sema::Compatible) &&
"Improper transparent union conversion") ? void (0) : __assert_fail
("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4522, __extension__ __PRETTY_FUNCTION__))
4522 "Improper transparent union conversion")(static_cast <bool> ((ConvTy == Sema::Compatible) &&
"Improper transparent union conversion") ? void (0) : __assert_fail
("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4522, __extension__ __PRETTY_FUNCTION__))
; 4523 (void)ConvTy; 4524 break; 4525 } 4526 4527 case ICK_Zero_Event_Conversion: 4528 case ICK_Zero_Queue_Conversion: 4529 From = ImpCastExprToType(From, ToType, 4530 CK_ZeroToOCLOpaqueType, 4531 From->getValueKind()).get(); 4532 break; 4533 4534 case ICK_Lvalue_To_Rvalue: 4535 case ICK_Array_To_Pointer: 4536 case ICK_Function_To_Pointer: 4537 case ICK_Function_Conversion: 4538 case ICK_Qualification: 4539 case ICK_Num_Conversion_Kinds: 4540 case ICK_C_Only_Conversion: 4541 case ICK_Incompatible_Pointer_Conversion: 4542 llvm_unreachable("Improper second standard conversion")::llvm::llvm_unreachable_internal("Improper second standard conversion"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4542)
; 4543 } 4544 4545 switch (SCS.Third) { 4546 case ICK_Identity: 4547 // Nothing to do. 4548 break; 4549 4550 case ICK_Function_Conversion: 4551 // If both sides are functions (or pointers/references to them), there could 4552 // be incompatible exception declarations. 4553 if (CheckExceptionSpecCompatibility(From, ToType)) 4554 return ExprError(); 4555 4556 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue, 4557 /*BasePath=*/nullptr, CCK) 4558 .get(); 4559 break; 4560 4561 case ICK_Qualification: { 4562 ExprValueKind VK = From->getValueKind(); 4563 CastKind CK = CK_NoOp; 4564 4565 if (ToType->isReferenceType() && 4566 ToType->getPointeeType().getAddressSpace() != 4567 From->getType().getAddressSpace()) 4568 CK = CK_AddressSpaceConversion; 4569 4570 if (ToType->isPointerType() && 4571 ToType->getPointeeType().getAddressSpace() != 4572 From->getType()->getPointeeType().getAddressSpace()) 4573 CK = CK_AddressSpaceConversion; 4574 4575 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK, 4576 /*BasePath=*/nullptr, CCK) 4577 .get(); 4578 4579 if (SCS.DeprecatedStringLiteralToCharPtr && 4580 !getLangOpts().WritableStrings) { 4581 Diag(From->getBeginLoc(), 4582 getLangOpts().CPlusPlus11 4583 ? diag::ext_deprecated_string_literal_conversion 4584 : diag::warn_deprecated_string_literal_conversion) 4585 << ToType.getNonReferenceType(); 4586 } 4587 4588 break; 4589 } 4590 4591 default: 4592 llvm_unreachable("Improper third standard conversion")::llvm::llvm_unreachable_internal("Improper third standard conversion"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4592)
; 4593 } 4594 4595 // If this conversion sequence involved a scalar -> atomic conversion, perform 4596 // that conversion now. 4597 if (!ToAtomicType.isNull()) { 4598 assert(Context.hasSameType((static_cast <bool> (Context.hasSameType( ToAtomicType->
castAs<AtomicType>()->getValueType(), From->getType
())) ? void (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4599, __extension__ __PRETTY_FUNCTION__))
4599 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()))(static_cast <bool> (Context.hasSameType( ToAtomicType->
castAs<AtomicType>()->getValueType(), From->getType
())) ? void (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4599, __extension__ __PRETTY_FUNCTION__))
; 4600 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, 4601 VK_PRValue, nullptr, CCK) 4602 .get(); 4603 } 4604 4605 // Materialize a temporary if we're implicitly converting to a reference 4606 // type. This is not required by the C++ rules but is necessary to maintain 4607 // AST invariants. 4608 if (ToType->isReferenceType() && From->isPRValue()) { 4609 ExprResult Res = TemporaryMaterializationConversion(From); 4610 if (Res.isInvalid()) 4611 return ExprError(); 4612 From = Res.get(); 4613 } 4614 4615 // If this conversion sequence succeeded and involved implicitly converting a 4616 // _Nullable type to a _Nonnull one, complain. 4617 if (!isCast(CCK)) 4618 diagnoseNullableToNonnullConversion(ToType, InitialFromType, 4619 From->getBeginLoc()); 4620 4621 return From; 4622} 4623 4624/// Check the completeness of a type in a unary type trait. 4625/// 4626/// If the particular type trait requires a complete type, tries to complete 4627/// it. If completing the type fails, a diagnostic is emitted and false 4628/// returned. If completing the type succeeds or no completion was required, 4629/// returns true. 4630static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, 4631 SourceLocation Loc, 4632 QualType ArgTy) { 4633 // C++0x [meta.unary.prop]p3: 4634 // For all of the class templates X declared in this Clause, instantiating 4635 // that template with a template argument that is a class template 4636 // specialization may result in the implicit instantiation of the template 4637 // argument if and only if the semantics of X require that the argument 4638 // must be a complete type. 4639 // We apply this rule to all the type trait expressions used to implement 4640 // these class templates. We also try to follow any GCC documented behavior 4641 // in these expressions to ensure portability of standard libraries. 4642 switch (UTT) { 4643 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4643)
; 4644 // is_complete_type somewhat obviously cannot require a complete type. 4645 case UTT_IsCompleteType: 4646 // Fall-through 4647 4648 // These traits are modeled on the type predicates in C++0x 4649 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as 4650 // requiring a complete type, as whether or not they return true cannot be 4651 // impacted by the completeness of the type. 4652 case UTT_IsVoid: 4653 case UTT_IsIntegral: 4654 case UTT_IsFloatingPoint: 4655 case UTT_IsArray: 4656 case UTT_IsPointer: 4657 case UTT_IsLvalueReference: 4658 case UTT_IsRvalueReference: 4659 case UTT_IsMemberFunctionPointer: 4660 case UTT_IsMemberObjectPointer: 4661 case UTT_IsEnum: 4662 case UTT_IsUnion: 4663 case UTT_IsClass: 4664 case UTT_IsFunction: 4665 case UTT_IsReference: 4666 case UTT_IsArithmetic: 4667 case UTT_IsFundamental: 4668 case UTT_IsObject: 4669 case UTT_IsScalar: 4670 case UTT_IsCompound: 4671 case UTT_IsMemberPointer: 4672 // Fall-through 4673 4674 // These traits are modeled on type predicates in C++0x [meta.unary.prop] 4675 // which requires some of its traits to have the complete type. However, 4676 // the completeness of the type cannot impact these traits' semantics, and 4677 // so they don't require it. This matches the comments on these traits in 4678 // Table 49. 4679 case UTT_IsConst: 4680 case UTT_IsVolatile: 4681 case UTT_IsSigned: 4682 case UTT_IsUnsigned: 4683 4684 // This type trait always returns false, checking the type is moot. 4685 case UTT_IsInterfaceClass: 4686 return true; 4687 4688 // C++14 [meta.unary.prop]: 4689 // If T is a non-union class type, T shall be a complete type. 4690 case UTT_IsEmpty: 4691 case UTT_IsPolymorphic: 4692 case UTT_IsAbstract: 4693 if (const auto *RD = ArgTy->getAsCXXRecordDecl()) 4694 if (!RD->isUnion()) 4695 return !S.RequireCompleteType( 4696 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 4697 return true; 4698 4699 // C++14 [meta.unary.prop]: 4700 // If T is a class type, T shall be a complete type. 4701 case UTT_IsFinal: 4702 case UTT_IsSealed: 4703 if (ArgTy->getAsCXXRecordDecl()) 4704 return !S.RequireCompleteType( 4705 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 4706 return true; 4707 4708 // C++1z [meta.unary.prop]: 4709 // remove_all_extents_t<T> shall be a complete type or cv void. 4710 case UTT_IsAggregate: 4711 case UTT_IsTrivial: 4712 case UTT_IsTriviallyCopyable: 4713 case UTT_IsStandardLayout: 4714 case UTT_IsPOD: 4715 case UTT_IsLiteral: 4716 // Per the GCC type traits documentation, T shall be a complete type, cv void, 4717 // or an array of unknown bound. But GCC actually imposes the same constraints 4718 // as above. 4719 case UTT_HasNothrowAssign: 4720 case UTT_HasNothrowMoveAssign: 4721 case UTT_HasNothrowConstructor: 4722 case UTT_HasNothrowCopy: 4723 case UTT_HasTrivialAssign: 4724 case UTT_HasTrivialMoveAssign: 4725 case UTT_HasTrivialDefaultConstructor: 4726 case UTT_HasTrivialMoveConstructor: 4727 case UTT_HasTrivialCopy: 4728 case UTT_HasTrivialDestructor: 4729 case UTT_HasVirtualDestructor: 4730 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); 4731 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 4732 4733 // C++1z [meta.unary.prop]: 4734 // T shall be a complete type, cv void, or an array of unknown bound. 4735 case UTT_IsDestructible: 4736 case UTT_IsNothrowDestructible: 4737 case UTT_IsTriviallyDestructible: 4738 case UTT_HasUniqueObjectRepresentations: 4739 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) 4740 return true; 4741 4742 return !S.RequireCompleteType( 4743 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 4744 } 4745} 4746 4747static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, 4748 Sema &Self, SourceLocation KeyLoc, ASTContext &C, 4749 bool (CXXRecordDecl::*HasTrivial)() const, 4750 bool (CXXRecordDecl::*HasNonTrivial)() const, 4751 bool (CXXMethodDecl::*IsDesiredOp)() const) 4752{ 4753 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4754 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) 4755 return true; 4756 4757 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); 4758 DeclarationNameInfo NameInfo(Name, KeyLoc); 4759 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); 4760 if (Self.LookupQualifiedName(Res, RD)) { 4761 bool FoundOperator = false; 4762 Res.suppressDiagnostics(); 4763 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 4764 Op != OpEnd; ++Op) { 4765 if (isa<FunctionTemplateDecl>(*Op)) 4766 continue; 4767 4768 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 4769 if((Operator->*IsDesiredOp)()) { 4770 FoundOperator = true; 4771 auto *CPT = Operator->getType()->castAs<FunctionProtoType>(); 4772 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 4773 if (!CPT || !CPT->isNothrow()) 4774 return false; 4775 } 4776 } 4777 return FoundOperator; 4778 } 4779 return false; 4780} 4781 4782static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, 4783 SourceLocation KeyLoc, QualType T) { 4784 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")(static_cast <bool> (!T->isDependentType() &&
"Cannot evaluate traits of dependent type") ? void (0) : __assert_fail
("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4784, __extension__ __PRETTY_FUNCTION__))
; 4785 4786 ASTContext &C = Self.Context; 4787 switch(UTT) { 4788 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 4788)
; 4789 // Type trait expressions corresponding to the primary type category 4790 // predicates in C++0x [meta.unary.cat]. 4791 case UTT_IsVoid: 4792 return T->isVoidType(); 4793 case UTT_IsIntegral: 4794 return T->isIntegralType(C); 4795 case UTT_IsFloatingPoint: 4796 return T->isFloatingType(); 4797 case UTT_IsArray: 4798 return T->isArrayType(); 4799 case UTT_IsPointer: 4800 return T->isAnyPointerType(); 4801 case UTT_IsLvalueReference: 4802 return T->isLValueReferenceType(); 4803 case UTT_IsRvalueReference: 4804 return T->isRValueReferenceType(); 4805 case UTT_IsMemberFunctionPointer: 4806 return T->isMemberFunctionPointerType(); 4807 case UTT_IsMemberObjectPointer: 4808 return T->isMemberDataPointerType(); 4809 case UTT_IsEnum: 4810 return T->isEnumeralType(); 4811 case UTT_IsUnion: 4812 return T->isUnionType(); 4813 case UTT_IsClass: 4814 return T->isClassType() || T->isStructureType() || T->isInterfaceType(); 4815 case UTT_IsFunction: 4816 return T->isFunctionType(); 4817 4818 // Type trait expressions which correspond to the convenient composition 4819 // predicates in C++0x [meta.unary.comp]. 4820 case UTT_IsReference: 4821 return T->isReferenceType(); 4822 case UTT_IsArithmetic: 4823 return T->isArithmeticType() && !T->isEnumeralType(); 4824 case UTT_IsFundamental: 4825 return T->isFundamentalType(); 4826 case UTT_IsObject: 4827 return T->isObjectType(); 4828 case UTT_IsScalar: 4829 // Note: semantic analysis depends on Objective-C lifetime types to be 4830 // considered scalar types. However, such types do not actually behave 4831 // like scalar types at run time (since they may require retain/release 4832 // operations), so we report them as non-scalar. 4833 if (T->isObjCLifetimeType()) { 4834 switch (T.getObjCLifetime()) { 4835 case Qualifiers::OCL_None: 4836 case Qualifiers::OCL_ExplicitNone: 4837 return true; 4838 4839 case Qualifiers::OCL_Strong: 4840 case Qualifiers::OCL_Weak: 4841 case Qualifiers::OCL_Autoreleasing: 4842 return false; 4843 } 4844 } 4845 4846 return T->isScalarType(); 4847 case UTT_IsCompound: 4848 return T->isCompoundType(); 4849 case UTT_IsMemberPointer: 4850 return T->isMemberPointerType(); 4851 4852 // Type trait expressions which correspond to the type property predicates 4853 // in C++0x [meta.unary.prop]. 4854 case UTT_IsConst: 4855 return T.isConstQualified(); 4856 case UTT_IsVolatile: 4857 return T.isVolatileQualified(); 4858 case UTT_IsTrivial: 4859 return T.isTrivialType(C); 4860 case UTT_IsTriviallyCopyable: 4861 return T.isTriviallyCopyableType(C); 4862 case UTT_IsStandardLayout: 4863 return T->isStandardLayoutType(); 4864 case UTT_IsPOD: 4865 return T.isPODType(C); 4866 case UTT_IsLiteral: 4867 return T->isLiteralType(C); 4868 case UTT_IsEmpty: 4869 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4870 return !RD->isUnion() && RD->isEmpty(); 4871 return false; 4872 case UTT_IsPolymorphic: 4873 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4874 return !RD->isUnion() && RD->isPolymorphic(); 4875 return false; 4876 case UTT_IsAbstract: 4877 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4878 return !RD->isUnion() && RD->isAbstract(); 4879 return false; 4880 case UTT_IsAggregate: 4881 // Report vector extensions and complex types as aggregates because they 4882 // support aggregate initialization. GCC mirrors this behavior for vectors 4883 // but not _Complex. 4884 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || 4885 T->isAnyComplexType(); 4886 // __is_interface_class only returns true when CL is invoked in /CLR mode and 4887 // even then only when it is used with the 'interface struct ...' syntax 4888 // Clang doesn't support /CLR which makes this type trait moot. 4889 case UTT_IsInterfaceClass: 4890 return false; 4891 case UTT_IsFinal: 4892 case UTT_IsSealed: 4893 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4894 return RD->hasAttr<FinalAttr>(); 4895 return false; 4896 case UTT_IsSigned: 4897 // Enum types should always return false. 4898 // Floating points should always return true. 4899 return T->isFloatingType() || 4900 (T->isSignedIntegerType() && !T->isEnumeralType()); 4901 case UTT_IsUnsigned: 4902 // Enum types should always return false. 4903 return T->isUnsignedIntegerType() && !T->isEnumeralType(); 4904 4905 // Type trait expressions which query classes regarding their construction, 4906 // destruction, and copying. Rather than being based directly on the 4907 // related type predicates in the standard, they are specified by both 4908 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those 4909 // specifications. 4910 // 4911 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html 4912 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 4913 // 4914 // Note that these builtins do not behave as documented in g++: if a class 4915 // has both a trivial and a non-trivial special member of a particular kind, 4916 // they return false! For now, we emulate this behavior. 4917 // FIXME: This appears to be a g++ bug: more complex cases reveal that it 4918 // does not correctly compute triviality in the presence of multiple special 4919 // members of the same kind. Revisit this once the g++ bug is fixed. 4920 case UTT_HasTrivialDefaultConstructor: 4921 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4922 // If __is_pod (type) is true then the trait is true, else if type is 4923 // a cv class or union type (or array thereof) with a trivial default 4924 // constructor ([class.ctor]) then the trait is true, else it is false. 4925 if (T.isPODType(C)) 4926 return true; 4927 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4928 return RD->hasTrivialDefaultConstructor() && 4929 !RD->hasNonTrivialDefaultConstructor(); 4930 return false; 4931 case UTT_HasTrivialMoveConstructor: 4932 // This trait is implemented by MSVC 2012 and needed to parse the 4933 // standard library headers. Specifically this is used as the logic 4934 // behind std::is_trivially_move_constructible (20.9.4.3). 4935 if (T.isPODType(C)) 4936 return true; 4937 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4938 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); 4939 return false; 4940 case UTT_HasTrivialCopy: 4941 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4942 // If __is_pod (type) is true or type is a reference type then 4943 // the trait is true, else if type is a cv class or union type 4944 // with a trivial copy constructor ([class.copy]) then the trait 4945 // is true, else it is false. 4946 if (T.isPODType(C) || T->isReferenceType()) 4947 return true; 4948 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4949 return RD->hasTrivialCopyConstructor() && 4950 !RD->hasNonTrivialCopyConstructor(); 4951 return false; 4952 case UTT_HasTrivialMoveAssign: 4953 // This trait is implemented by MSVC 2012 and needed to parse the 4954 // standard library headers. Specifically it is used as the logic 4955 // behind std::is_trivially_move_assignable (20.9.4.3) 4956 if (T.isPODType(C)) 4957 return true; 4958 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4959 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); 4960 return false; 4961 case UTT_HasTrivialAssign: 4962 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4963 // If type is const qualified or is a reference type then the 4964 // trait is false. Otherwise if __is_pod (type) is true then the 4965 // trait is true, else if type is a cv class or union type with 4966 // a trivial copy assignment ([class.copy]) then the trait is 4967 // true, else it is false. 4968 // Note: the const and reference restrictions are interesting, 4969 // given that const and reference members don't prevent a class 4970 // from having a trivial copy assignment operator (but do cause 4971 // errors if the copy assignment operator is actually used, q.v. 4972 // [class.copy]p12). 4973 4974 if (T.isConstQualified()) 4975 return false; 4976 if (T.isPODType(C)) 4977 return true; 4978 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4979 return RD->hasTrivialCopyAssignment() && 4980 !RD->hasNonTrivialCopyAssignment(); 4981 return false; 4982 case UTT_IsDestructible: 4983 case UTT_IsTriviallyDestructible: 4984 case UTT_IsNothrowDestructible: 4985 // C++14 [meta.unary.prop]: 4986 // For reference types, is_destructible<T>::value is true. 4987 if (T->isReferenceType()) 4988 return true; 4989 4990 // Objective-C++ ARC: autorelease types don't require destruction. 4991 if (T->isObjCLifetimeType() && 4992 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 4993 return true; 4994 4995 // C++14 [meta.unary.prop]: 4996 // For incomplete types and function types, is_destructible<T>::value is 4997 // false. 4998 if (T->isIncompleteType() || T->isFunctionType()) 4999 return false; 5000 5001 // A type that requires destruction (via a non-trivial destructor or ARC 5002 // lifetime semantics) is not trivially-destructible. 5003 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) 5004 return false; 5005 5006 // C++14 [meta.unary.prop]: 5007 // For object types and given U equal to remove_all_extents_t<T>, if the 5008 // expression std::declval<U&>().~U() is well-formed when treated as an 5009 // unevaluated operand (Clause 5), then is_destructible<T>::value is true 5010 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 5011 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); 5012 if (!Destructor) 5013 return false; 5014 // C++14 [dcl.fct.def.delete]p2: 5015 // A program that refers to a deleted function implicitly or 5016 // explicitly, other than to declare it, is ill-formed. 5017 if (Destructor->isDeleted()) 5018 return false; 5019 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) 5020 return false; 5021 if (UTT == UTT_IsNothrowDestructible) { 5022 auto *CPT = Destructor->getType()->castAs<FunctionProtoType>(); 5023 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 5024 if (!CPT || !CPT->isNothrow()) 5025 return false; 5026 } 5027 } 5028 return true; 5029 5030 case UTT_HasTrivialDestructor: 5031 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 5032 // If __is_pod (type) is true or type is a reference type 5033 // then the trait is true, else if type is a cv class or union 5034 // type (or array thereof) with a trivial destructor 5035 // ([class.dtor]) then the trait is true, else it is 5036 // false. 5037 if (T.isPODType(C) || T->isReferenceType()) 5038 return true; 5039 5040 // Objective-C++ ARC: autorelease types don't require destruction. 5041 if (T->isObjCLifetimeType() && 5042 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 5043 return true; 5044 5045 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 5046 return RD->hasTrivialDestructor(); 5047 return false; 5048 // TODO: Propagate nothrowness for implicitly declared special members. 5049 case UTT_HasNothrowAssign: 5050 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 5051 // If type is const qualified or is a reference type then the 5052 // trait is false. Otherwise if __has_trivial_assign (type) 5053 // is true then the trait is true, else if type is a cv class 5054 // or union type with copy assignment operators that are known 5055 // not to throw an exception then the trait is true, else it is 5056 // false. 5057 if (C.getBaseElementType(T).isConstQualified()) 5058 return false; 5059 if (T->isReferenceType()) 5060 return false; 5061 if (T.isPODType(C) || T->isObjCLifetimeType()) 5062 return true; 5063 5064 if (const RecordType *RT = T->getAs<RecordType>()) 5065 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 5066 &CXXRecordDecl::hasTrivialCopyAssignment, 5067 &CXXRecordDecl::hasNonTrivialCopyAssignment, 5068 &CXXMethodDecl::isCopyAssignmentOperator); 5069 return false; 5070 case UTT_HasNothrowMoveAssign: 5071 // This trait is implemented by MSVC 2012 and needed to parse the 5072 // standard library headers. Specifically this is used as the logic 5073 // behind std::is_nothrow_move_assignable (20.9.4.3). 5074 if (T.isPODType(C)) 5075 return true; 5076 5077 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) 5078 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 5079 &CXXRecordDecl::hasTrivialMoveAssignment, 5080 &CXXRecordDecl::hasNonTrivialMoveAssignment, 5081 &CXXMethodDecl::isMoveAssignmentOperator); 5082 return false; 5083 case UTT_HasNothrowCopy: 5084 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 5085 // If __has_trivial_copy (type) is true then the trait is true, else 5086 // if type is a cv class or union type with copy constructors that are 5087 // known not to throw an exception then the trait is true, else it is 5088 // false. 5089 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) 5090 return true; 5091 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 5092 if (RD->hasTrivialCopyConstructor() && 5093 !RD->hasNonTrivialCopyConstructor()) 5094 return true; 5095 5096 bool FoundConstructor = false; 5097 unsigned FoundTQs; 5098 for (const auto *ND : Self.LookupConstructors(RD)) { 5099 // A template constructor is never a copy constructor. 5100 // FIXME: However, it may actually be selected at the actual overload 5101 // resolution point. 5102 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 5103 continue; 5104 // UsingDecl itself is not a constructor 5105 if (isa<UsingDecl>(ND)) 5106 continue; 5107 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 5108 if (Constructor->isCopyConstructor(FoundTQs)) { 5109 FoundConstructor = true; 5110 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); 5111 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 5112 if (!CPT) 5113 return false; 5114 // TODO: check whether evaluating default arguments can throw. 5115 // For now, we'll be conservative and assume that they can throw. 5116 if (!CPT->isNothrow() || CPT->getNumParams() > 1) 5117 return false; 5118 } 5119 } 5120 5121 return FoundConstructor; 5122 } 5123 return false; 5124 case UTT_HasNothrowConstructor: 5125 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 5126 // If __has_trivial_constructor (type) is true then the trait is 5127 // true, else if type is a cv class or union type (or array 5128 // thereof) with a default constructor that is known not to 5129 // throw an exception then the trait is true, else it is false. 5130 if (T.isPODType(C) || T->isObjCLifetimeType()) 5131 return true; 5132 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 5133 if (RD->hasTrivialDefaultConstructor() && 5134 !RD->hasNonTrivialDefaultConstructor()) 5135 return true; 5136 5137 bool FoundConstructor = false; 5138 for (const auto *ND : Self.LookupConstructors(RD)) { 5139 // FIXME: In C++0x, a constructor template can be a default constructor. 5140 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 5141 continue; 5142 // UsingDecl itself is not a constructor 5143 if (isa<UsingDecl>(ND)) 5144 continue; 5145 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 5146 if (Constructor->isDefaultConstructor()) { 5147 FoundConstructor = true; 5148 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); 5149 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 5150 if (!CPT) 5151 return false; 5152 // FIXME: check whether evaluating default arguments can throw. 5153 // For now, we'll be conservative and assume that they can throw. 5154 if (!CPT->isNothrow() || CPT->getNumParams() > 0) 5155 return false; 5156 } 5157 } 5158 return FoundConstructor; 5159 } 5160 return false; 5161 case UTT_HasVirtualDestructor: 5162 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 5163 // If type is a class type with a virtual destructor ([class.dtor]) 5164 // then the trait is true, else it is false. 5165 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 5166 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 5167 return Destructor->isVirtual(); 5168 return false; 5169 5170 // These type trait expressions are modeled on the specifications for the 5171 // Embarcadero C++0x type trait functions: 5172 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 5173 case UTT_IsCompleteType: 5174 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): 5175 // Returns True if and only if T is a complete type at the point of the 5176 // function call. 5177 return !T->isIncompleteType(); 5178 case UTT_HasUniqueObjectRepresentations: 5179 return C.hasUniqueObjectRepresentations(T); 5180 } 5181} 5182 5183static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 5184 QualType RhsT, SourceLocation KeyLoc); 5185 5186static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, 5187 ArrayRef<TypeSourceInfo *> Args, 5188 SourceLocation RParenLoc) { 5189 if (Kind <= UTT_Last) 5190 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType()); 5191 5192 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible 5193 // traits to avoid duplication. 5194 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary) 5195 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(), 5196 Args[1]->getType(), RParenLoc); 5197 5198 switch (Kind) { 5199 case clang::BTT_ReferenceBindsToTemporary: 5200 case clang::TT_IsConstructible: 5201 case clang::TT_IsNothrowConstructible: 5202 case clang::TT_IsTriviallyConstructible: { 5203 // C++11 [meta.unary.prop]: 5204 // is_trivially_constructible is defined as: 5205 // 5206 // is_constructible<T, Args...>::value is true and the variable 5207 // definition for is_constructible, as defined below, is known to call 5208 // no operation that is not trivial. 5209 // 5210 // The predicate condition for a template specialization 5211 // is_constructible<T, Args...> shall be satisfied if and only if the 5212 // following variable definition would be well-formed for some invented 5213 // variable t: 5214 // 5215 // T t(create<Args>()...); 5216 assert(!Args.empty())(static_cast <bool> (!Args.empty()) ? void (0) : __assert_fail
("!Args.empty()", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5216, __extension__ __PRETTY_FUNCTION__))
; 5217 5218 // Precondition: T and all types in the parameter pack Args shall be 5219 // complete types, (possibly cv-qualified) void, or arrays of 5220 // unknown bound. 5221 for (const auto *TSI : Args) { 5222 QualType ArgTy = TSI->getType(); 5223 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) 5224 continue; 5225 5226 if (S.RequireCompleteType(KWLoc, ArgTy, 5227 diag::err_incomplete_type_used_in_type_trait_expr)) 5228 return false; 5229 } 5230 5231 // Make sure the first argument is not incomplete nor a function type. 5232 QualType T = Args[0]->getType(); 5233 if (T->isIncompleteType() || T->isFunctionType()) 5234 return false; 5235 5236 // Make sure the first argument is not an abstract type. 5237 CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5238 if (RD && RD->isAbstract()) 5239 return false; 5240 5241 llvm::BumpPtrAllocator OpaqueExprAllocator; 5242 SmallVector<Expr *, 2> ArgExprs; 5243 ArgExprs.reserve(Args.size() - 1); 5244 for (unsigned I = 1, N = Args.size(); I != N; ++I) { 5245 QualType ArgTy = Args[I]->getType(); 5246 if (ArgTy->isObjectType() || ArgTy->isFunctionType()) 5247 ArgTy = S.Context.getRValueReferenceType(ArgTy); 5248 ArgExprs.push_back( 5249 new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>()) 5250 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(), 5251 ArgTy.getNonLValueExprType(S.Context), 5252 Expr::getValueKindForType(ArgTy))); 5253 } 5254 5255 // Perform the initialization in an unevaluated context within a SFINAE 5256 // trap at translation unit scope. 5257 EnterExpressionEvaluationContext Unevaluated( 5258 S, Sema::ExpressionEvaluationContext::Unevaluated); 5259 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 5260 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 5261 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0])); 5262 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, 5263 RParenLoc)); 5264 InitializationSequence Init(S, To, InitKind, ArgExprs); 5265 if (Init.Failed()) 5266 return false; 5267 5268 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); 5269 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 5270 return false; 5271 5272 if (Kind == clang::TT_IsConstructible) 5273 return true; 5274 5275 if (Kind == clang::BTT_ReferenceBindsToTemporary) { 5276 if (!T->isReferenceType()) 5277 return false; 5278 5279 return !Init.isDirectReferenceBinding(); 5280 } 5281 5282 if (Kind == clang::TT_IsNothrowConstructible) 5283 return S.canThrow(Result.get()) == CT_Cannot; 5284 5285 if (Kind == clang::TT_IsTriviallyConstructible) { 5286 // Under Objective-C ARC and Weak, if the destination has non-trivial 5287 // Objective-C lifetime, this is a non-trivial construction. 5288 if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) 5289 return false; 5290 5291 // The initialization succeeded; now make sure there are no non-trivial 5292 // calls. 5293 return !Result.get()->hasNonTrivialCall(S.Context); 5294 } 5295 5296 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5296)
; 5297 return false; 5298 } 5299 default: llvm_unreachable("not a TT")::llvm::llvm_unreachable_internal("not a TT", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5299)
; 5300 } 5301 5302 return false; 5303} 5304 5305ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 5306 ArrayRef<TypeSourceInfo *> Args, 5307 SourceLocation RParenLoc) { 5308 QualType ResultType = Context.getLogicalOperationType(); 5309 5310 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( 5311 *this, Kind, KWLoc, Args[0]->getType())) 5312 return ExprError(); 5313 5314 bool Dependent = false; 5315 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 5316 if (Args[I]->getType()->isDependentType()) { 5317 Dependent = true; 5318 break; 5319 } 5320 } 5321 5322 bool Result = false; 5323 if (!Dependent) 5324 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); 5325 5326 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args, 5327 RParenLoc, Result); 5328} 5329 5330ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 5331 ArrayRef<ParsedType> Args, 5332 SourceLocation RParenLoc) { 5333 SmallVector<TypeSourceInfo *, 4> ConvertedArgs; 5334 ConvertedArgs.reserve(Args.size()); 5335 5336 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 5337 TypeSourceInfo *TInfo; 5338 QualType T = GetTypeFromParser(Args[I], &TInfo); 5339 if (!TInfo) 5340 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); 5341 5342 ConvertedArgs.push_back(TInfo); 5343 } 5344 5345 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); 5346} 5347 5348static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 5349 QualType RhsT, SourceLocation KeyLoc) { 5350 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&(static_cast <bool> (!LhsT->isDependentType() &&
!RhsT->isDependentType() && "Cannot evaluate traits of dependent types"
) ? void (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5351, __extension__ __PRETTY_FUNCTION__))
5351 "Cannot evaluate traits of dependent types")(static_cast <bool> (!LhsT->isDependentType() &&
!RhsT->isDependentType() && "Cannot evaluate traits of dependent types"
) ? void (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5351, __extension__ __PRETTY_FUNCTION__))
; 5352 5353 switch(BTT) { 5354 case BTT_IsBaseOf: { 5355 // C++0x [meta.rel]p2 5356 // Base is a base class of Derived without regard to cv-qualifiers or 5357 // Base and Derived are not unions and name the same class type without 5358 // regard to cv-qualifiers. 5359 5360 const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 5361 const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 5362 if (!rhsRecord || !lhsRecord) { 5363 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); 5364 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); 5365 if (!LHSObjTy || !RHSObjTy) 5366 return false; 5367 5368 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); 5369 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); 5370 if (!BaseInterface || !DerivedInterface) 5371 return false; 5372 5373 if (Self.RequireCompleteType( 5374 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr)) 5375 return false; 5376 5377 return BaseInterface->isSuperClassOf(DerivedInterface); 5378 } 5379 5380 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)(static_cast <bool> (Self.Context.hasSameUnqualifiedType
(LhsT, RhsT) == (lhsRecord == rhsRecord)) ? void (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5381, __extension__ __PRETTY_FUNCTION__))
5381 == (lhsRecord == rhsRecord))(static_cast <bool> (Self.Context.hasSameUnqualifiedType
(LhsT, RhsT) == (lhsRecord == rhsRecord)) ? void (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5381, __extension__ __PRETTY_FUNCTION__))
; 5382 5383 // Unions are never base classes, and never have base classes. 5384 // It doesn't matter if they are complete or not. See PR#41843 5385 if (lhsRecord && lhsRecord->getDecl()->isUnion()) 5386 return false; 5387 if (rhsRecord && rhsRecord->getDecl()->isUnion()) 5388 return false; 5389 5390 if (lhsRecord == rhsRecord) 5391 return true; 5392 5393 // C++0x [meta.rel]p2: 5394 // If Base and Derived are class types and are different types 5395 // (ignoring possible cv-qualifiers) then Derived shall be a 5396 // complete type. 5397 if (Self.RequireCompleteType(KeyLoc, RhsT, 5398 diag::err_incomplete_type_used_in_type_trait_expr)) 5399 return false; 5400 5401 return cast<CXXRecordDecl>(rhsRecord->getDecl()) 5402 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 5403 } 5404 case BTT_IsSame: 5405 return Self.Context.hasSameType(LhsT, RhsT); 5406 case BTT_TypeCompatible: { 5407 // GCC ignores cv-qualifiers on arrays for this builtin. 5408 Qualifiers LhsQuals, RhsQuals; 5409 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals); 5410 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals); 5411 return Self.Context.typesAreCompatible(Lhs, Rhs); 5412 } 5413 case BTT_IsConvertible: 5414 case BTT_IsConvertibleTo: { 5415 // C++0x [meta.rel]p4: 5416 // Given the following function prototype: 5417 // 5418 // template <class T> 5419 // typename add_rvalue_reference<T>::type create(); 5420 // 5421 // the predicate condition for a template specialization 5422 // is_convertible<From, To> shall be satisfied if and only if 5423 // the return expression in the following code would be 5424 // well-formed, including any implicit conversions to the return 5425 // type of the function: 5426 // 5427 // To test() { 5428 // return create<From>(); 5429 // } 5430 // 5431 // Access checking is performed as if in a context unrelated to To and 5432 // From. Only the validity of the immediate context of the expression 5433 // of the return-statement (including conversions to the return type) 5434 // is considered. 5435 // 5436 // We model the initialization as a copy-initialization of a temporary 5437 // of the appropriate type, which for this expression is identical to the 5438 // return statement (since NRVO doesn't apply). 5439 5440 // Functions aren't allowed to return function or array types. 5441 if (RhsT->isFunctionType() || RhsT->isArrayType()) 5442 return false; 5443 5444 // A return statement in a void function must have void type. 5445 if (RhsT->isVoidType()) 5446 return LhsT->isVoidType(); 5447 5448 // A function definition requires a complete, non-abstract return type. 5449 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT)) 5450 return false; 5451 5452 // Compute the result of add_rvalue_reference. 5453 if (LhsT->isObjectType() || LhsT->isFunctionType()) 5454 LhsT = Self.Context.getRValueReferenceType(LhsT); 5455 5456 // Build a fake source and destination for initialization. 5457 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 5458 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 5459 Expr::getValueKindForType(LhsT)); 5460 Expr *FromPtr = &From; 5461 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 5462 SourceLocation())); 5463 5464 // Perform the initialization in an unevaluated context within a SFINAE 5465 // trap at translation unit scope. 5466 EnterExpressionEvaluationContext Unevaluated( 5467 Self, Sema::ExpressionEvaluationContext::Unevaluated); 5468 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 5469 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 5470 InitializationSequence Init(Self, To, Kind, FromPtr); 5471 if (Init.Failed()) 5472 return false; 5473 5474 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); 5475 return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); 5476 } 5477 5478 case BTT_IsAssignable: 5479 case BTT_IsNothrowAssignable: 5480 case BTT_IsTriviallyAssignable: { 5481 // C++11 [meta.unary.prop]p3: 5482 // is_trivially_assignable is defined as: 5483 // is_assignable<T, U>::value is true and the assignment, as defined by 5484 // is_assignable, is known to call no operation that is not trivial 5485 // 5486 // is_assignable is defined as: 5487 // The expression declval<T>() = declval<U>() is well-formed when 5488 // treated as an unevaluated operand (Clause 5). 5489 // 5490 // For both, T and U shall be complete types, (possibly cv-qualified) 5491 // void, or arrays of unknown bound. 5492 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 5493 Self.RequireCompleteType(KeyLoc, LhsT, 5494 diag::err_incomplete_type_used_in_type_trait_expr)) 5495 return false; 5496 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 5497 Self.RequireCompleteType(KeyLoc, RhsT, 5498 diag::err_incomplete_type_used_in_type_trait_expr)) 5499 return false; 5500 5501 // cv void is never assignable. 5502 if (LhsT->isVoidType() || RhsT->isVoidType()) 5503 return false; 5504 5505 // Build expressions that emulate the effect of declval<T>() and 5506 // declval<U>(). 5507 if (LhsT->isObjectType() || LhsT->isFunctionType()) 5508 LhsT = Self.Context.getRValueReferenceType(LhsT); 5509 if (RhsT->isObjectType() || RhsT->isFunctionType()) 5510 RhsT = Self.Context.getRValueReferenceType(RhsT); 5511 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 5512 Expr::getValueKindForType(LhsT)); 5513 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), 5514 Expr::getValueKindForType(RhsT)); 5515 5516 // Attempt the assignment in an unevaluated context within a SFINAE 5517 // trap at translation unit scope. 5518 EnterExpressionEvaluationContext Unevaluated( 5519 Self, Sema::ExpressionEvaluationContext::Unevaluated); 5520 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 5521 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 5522 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, 5523 &Rhs); 5524 if (Result.isInvalid()) 5525 return false; 5526 5527 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile. 5528 Self.CheckUnusedVolatileAssignment(Result.get()); 5529 5530 if (SFINAE.hasErrorOccurred()) 5531 return false; 5532 5533 if (BTT == BTT_IsAssignable) 5534 return true; 5535 5536 if (BTT == BTT_IsNothrowAssignable) 5537 return Self.canThrow(Result.get()) == CT_Cannot; 5538 5539 if (BTT == BTT_IsTriviallyAssignable) { 5540 // Under Objective-C ARC and Weak, if the destination has non-trivial 5541 // Objective-C lifetime, this is a non-trivial assignment. 5542 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) 5543 return false; 5544 5545 return !Result.get()->hasNonTrivialCall(Self.Context); 5546 } 5547 5548 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5548)
; 5549 return false; 5550 } 5551 default: llvm_unreachable("not a BTT")::llvm::llvm_unreachable_internal("not a BTT", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5551)
; 5552 } 5553 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5553)
; 5554} 5555 5556ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, 5557 SourceLocation KWLoc, 5558 ParsedType Ty, 5559 Expr* DimExpr, 5560 SourceLocation RParen) { 5561 TypeSourceInfo *TSInfo; 5562 QualType T = GetTypeFromParser(Ty, &TSInfo); 5563 if (!TSInfo) 5564 TSInfo = Context.getTrivialTypeSourceInfo(T); 5565 5566 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); 5567} 5568 5569static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, 5570 QualType T, Expr *DimExpr, 5571 SourceLocation KeyLoc) { 5572 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")(static_cast <bool> (!T->isDependentType() &&
"Cannot evaluate traits of dependent type") ? void (0) : __assert_fail
("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5572, __extension__ __PRETTY_FUNCTION__))
; 5573 5574 switch(ATT) { 5575 case ATT_ArrayRank: 5576 if (T->isArrayType()) { 5577 unsigned Dim = 0; 5578 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 5579 ++Dim; 5580 T = AT->getElementType(); 5581 } 5582 return Dim; 5583 } 5584 return 0; 5585 5586 case ATT_ArrayExtent: { 5587 llvm::APSInt Value; 5588 uint64_t Dim; 5589 if (Self.VerifyIntegerConstantExpression( 5590 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer) 5591 .isInvalid()) 5592 return 0; 5593 if (Value.isSigned() && Value.isNegative()) { 5594 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) 5595 << DimExpr->getSourceRange(); 5596 return 0; 5597 } 5598 Dim = Value.getLimitedValue(); 5599 5600 if (T->isArrayType()) { 5601 unsigned D = 0; 5602 bool Matched = false; 5603 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 5604 if (Dim == D) { 5605 Matched = true; 5606 break; 5607 } 5608 ++D; 5609 T = AT->getElementType(); 5610 } 5611 5612 if (Matched && T->isArrayType()) { 5613 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) 5614 return CAT->getSize().getLimitedValue(); 5615 } 5616 } 5617 return 0; 5618 } 5619 } 5620 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5620)
; 5621} 5622 5623ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, 5624 SourceLocation KWLoc, 5625 TypeSourceInfo *TSInfo, 5626 Expr* DimExpr, 5627 SourceLocation RParen) { 5628 QualType T = TSInfo->getType(); 5629 5630 // FIXME: This should likely be tracked as an APInt to remove any host 5631 // assumptions about the width of size_t on the target. 5632 uint64_t Value = 0; 5633 if (!T->isDependentType()) 5634 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); 5635 5636 // While the specification for these traits from the Embarcadero C++ 5637 // compiler's documentation says the return type is 'unsigned int', Clang 5638 // returns 'size_t'. On Windows, the primary platform for the Embarcadero 5639 // compiler, there is no difference. On several other platforms this is an 5640 // important distinction. 5641 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, 5642 RParen, Context.getSizeType()); 5643} 5644 5645ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, 5646 SourceLocation KWLoc, 5647 Expr *Queried, 5648 SourceLocation RParen) { 5649 // If error parsing the expression, ignore. 5650 if (!Queried) 5651 return ExprError(); 5652 5653 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); 5654 5655 return Result; 5656} 5657 5658static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { 5659 switch (ET) { 5660 case ET_IsLValueExpr: return E->isLValue(); 5661 case ET_IsRValueExpr: 5662 return E->isPRValue(); 5663 } 5664 llvm_unreachable("Expression trait not covered by switch")::llvm::llvm_unreachable_internal("Expression trait not covered by switch"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5664)
; 5665} 5666 5667ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, 5668 SourceLocation KWLoc, 5669 Expr *Queried, 5670 SourceLocation RParen) { 5671 if (Queried->isTypeDependent()) { 5672 // Delay type-checking for type-dependent expressions. 5673 } else if (Queried->getType()->isPlaceholderType()) { 5674 ExprResult PE = CheckPlaceholderExpr(Queried); 5675 if (PE.isInvalid()) return ExprError(); 5676 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen); 5677 } 5678 5679 bool Value = EvaluateExpressionTrait(ET, Queried); 5680 5681 return new (Context) 5682 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); 5683} 5684 5685QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, 5686 ExprValueKind &VK, 5687 SourceLocation Loc, 5688 bool isIndirect) { 5689 assert(!LHS.get()->getType()->isPlaceholderType() &&(static_cast <bool> (!LHS.get()->getType()->isPlaceholderType
() && !RHS.get()->getType()->isPlaceholderType(
) && "placeholders should have been weeded out by now"
) ? void (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5691, __extension__ __PRETTY_FUNCTION__))
5690 !RHS.get()->getType()->isPlaceholderType() &&(static_cast <bool> (!LHS.get()->getType()->isPlaceholderType
() && !RHS.get()->getType()->isPlaceholderType(
) && "placeholders should have been weeded out by now"
) ? void (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5691, __extension__ __PRETTY_FUNCTION__))
5691 "placeholders should have been weeded out by now")(static_cast <bool> (!LHS.get()->getType()->isPlaceholderType
() && !RHS.get()->getType()->isPlaceholderType(
) && "placeholders should have been weeded out by now"
) ? void (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/clang/lib/Sema/SemaExprCXX.cpp"
, 5691, __extension__ __PRETTY_FUNCTION__))
; 5692 5693 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the 5694 // temporary materialization conversion otherwise. 5695 if (isIndirect) 5696 LHS = DefaultLvalueConversion(LHS.get()); 5697 else if (LHS.get()->isPRValue()) 5698 LHS = TemporaryMaterializationConversion(LHS.get()); 5699 if (LHS.isInvalid()) 5700 return QualType(); 5701 5702 // The RHS always undergoes lvalue conversions. 5703 RHS = DefaultLvalueConversion(RHS.get()); 5704 if (RHS.isInvalid()) return QualType(); 5705 5706 const char *OpSpelling = isIndirect ? "->*" : ".*"; 5707 // C++ 5.5p2 5708 // The binary operator .* [p3: ->*] binds its second operand, which shall 5709 // be of type "pointer to member of T" (where T is a completely-defined 5710 // class type) [...] 5711 QualType RHSType = RHS.get()->getType(); 5712 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); 5713 if (!MemPtr) { 5714 Diag(Loc, diag::err_bad_memptr_rhs) 5715 << OpSpelling << RHSType << RHS.get()->getSourceRange(); 5716 return QualType(); 5717 } 5718 5719 QualType Class(MemPtr->getClass(), 0); 5720 5721 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 5722 // member pointer points must be completely-defined. However, there is no 5723 // reason for this semantic distinction, and the rule is not enforced by 5724 // other compilers. Therefore, we do not check this property, as it is 5725 // likely to be considered a defect. 5726 5727 // C++ 5.5p2 5728 // [...] to its first operand, which shall be of class T or of a class of 5729 // which T is an unambiguous and accessible base class. [p3: a pointer to 5730 // such a class] 5731 QualType LHSType = LHS.get()->getType(); 5732 if (isIndirect) { 5733 if (const PointerType *Ptr = LHSType->getAs<PointerType>()) 5734 LHSType = Ptr->getPointeeType(); 5735 else { 5736 Diag(Loc, diag::err_bad_memptr_lhs) 5737 << OpSpelling << 1 << LHSType 5738 << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 5739 return QualType(); 5740 } 5741 } 5742 5743 if (!Context.hasSameUnqualifiedType(Class, LHSType)) { 5744 // If we want to check the hierarchy, we need a complete type. 5745 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, 5746 OpSpelling, (int)isIndirect)) { 5747 return QualType(); 5748 } 5749 5750 if (!IsDerivedFrom(Loc, LHSType, Class)) { 5751 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 5752 << (int)isIndirect << LHS.get()->getType(); 5753 return QualType(); 5754 } 5755 5756 CXXCastPath BasePath; 5757 if (CheckDerivedToBaseConversion( 5758 LHSType, Class, Loc, 5759 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), 5760 &BasePath)) 5761 return QualType(); 5762 5763 // Cast LHS to type of use. 5764 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers()); 5765 if (isIndirect) 5766 UseType = Context.getPointerType(UseType); 5767 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind(); 5768 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, 5769 &BasePath); 5770 } 5771 5772 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { 5773 // Diagnose use of pointer-to-member type which when used as 5774 // the functional cast in a pointer-to-member expression. 5775 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 5776 return QualType(); 5777 } 5778 5779 // C++ 5.5p2 5780 // The result is an object or a function of the type specified by the 5781 // second operand. 5782 // The cv qualifiers are the union of those in the pointer and the left side, 5783 // in accordance with 5.5p5 and 5.2.5. 5784 QualType Result = MemPtr->getPointeeType(); 5785 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); 5786 5787 // C++0x [expr.mptr.oper]p6: 5788 // In a .* expression whose object expression is an rvalue, the program is 5789 // ill-formed if the second operand is a pointer to member function with 5790 // ref-qualifier &. In a ->* expression or in a .* expression whose object 5791 // expression is an lvalue, the program is ill-formed if the second operand 5792 // is a pointer to member function with ref-qualifier &&. 5793 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 5794 switch (Proto->getRefQualifier()) { 5795 case RQ_None: 5796 // Do nothing