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