Bug Summary

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