Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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