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