File: | build/source/clang/lib/Sema/SemaExprCXX.cpp |
Warning: | line 2017, column 47 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | /// | |||
9 | /// \file | |||
10 | /// Implements semantic analysis for C++ expressions. | |||
11 | /// | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "TreeTransform.h" | |||
15 | #include "TypeLocBuilder.h" | |||
16 | #include "clang/AST/ASTContext.h" | |||
17 | #include "clang/AST/ASTLambda.h" | |||
18 | #include "clang/AST/CXXInheritance.h" | |||
19 | #include "clang/AST/CharUnits.h" | |||
20 | #include "clang/AST/DeclObjC.h" | |||
21 | #include "clang/AST/ExprCXX.h" | |||
22 | #include "clang/AST/ExprObjC.h" | |||
23 | #include "clang/AST/RecursiveASTVisitor.h" | |||
24 | #include "clang/AST/Type.h" | |||
25 | #include "clang/AST/TypeLoc.h" | |||
26 | #include "clang/Basic/AlignedAllocation.h" | |||
27 | #include "clang/Basic/DiagnosticSema.h" | |||
28 | #include "clang/Basic/PartialDiagnostic.h" | |||
29 | #include "clang/Basic/TargetInfo.h" | |||
30 | #include "clang/Basic/TokenKinds.h" | |||
31 | #include "clang/Basic/TypeTraits.h" | |||
32 | #include "clang/Lex/Preprocessor.h" | |||
33 | #include "clang/Sema/DeclSpec.h" | |||
34 | #include "clang/Sema/Initialization.h" | |||
35 | #include "clang/Sema/Lookup.h" | |||
36 | #include "clang/Sema/ParsedTemplate.h" | |||
37 | #include "clang/Sema/Scope.h" | |||
38 | #include "clang/Sema/ScopeInfo.h" | |||
39 | #include "clang/Sema/SemaInternal.h" | |||
40 | #include "clang/Sema/SemaLambda.h" | |||
41 | #include "clang/Sema/Template.h" | |||
42 | #include "clang/Sema/TemplateDeduction.h" | |||
43 | #include "llvm/ADT/APInt.h" | |||
44 | #include "llvm/ADT/STLExtras.h" | |||
45 | #include "llvm/Support/ErrorHandling.h" | |||
46 | #include "llvm/Support/TypeSize.h" | |||
47 | using namespace clang; | |||
48 | using namespace sema; | |||
49 | ||||
50 | /// Handle the result of the special case name lookup for inheriting | |||
51 | /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as | |||
52 | /// constructor names in member using declarations, even if 'X' is not the | |||
53 | /// name of the corresponding type. | |||
54 | ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, | |||
55 | SourceLocation NameLoc, | |||
56 | IdentifierInfo &Name) { | |||
57 | NestedNameSpecifier *NNS = SS.getScopeRep(); | |||
58 | ||||
59 | // Convert the nested-name-specifier into a type. | |||
60 | QualType Type; | |||
61 | switch (NNS->getKind()) { | |||
62 | case NestedNameSpecifier::TypeSpec: | |||
63 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
64 | Type = QualType(NNS->getAsType(), 0); | |||
65 | break; | |||
66 | ||||
67 | case NestedNameSpecifier::Identifier: | |||
68 | // Strip off the last layer of the nested-name-specifier and build a | |||
69 | // typename type for it. | |||
70 | assert(NNS->getAsIdentifier() == &Name && "not a constructor name")(static_cast <bool> (NNS->getAsIdentifier() == & Name && "not a constructor name") ? void (0) : __assert_fail ("NNS->getAsIdentifier() == &Name && \"not a constructor name\"" , "clang/lib/Sema/SemaExprCXX.cpp", 70, __extension__ __PRETTY_FUNCTION__ )); | |||
71 | Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(), | |||
72 | NNS->getAsIdentifier()); | |||
73 | break; | |||
74 | ||||
75 | case NestedNameSpecifier::Global: | |||
76 | case NestedNameSpecifier::Super: | |||
77 | case NestedNameSpecifier::Namespace: | |||
78 | case NestedNameSpecifier::NamespaceAlias: | |||
79 | llvm_unreachable("Nested name specifier is not a type for inheriting ctor")::llvm::llvm_unreachable_internal("Nested name specifier is not a type for inheriting ctor" , "clang/lib/Sema/SemaExprCXX.cpp", 79); | |||
80 | } | |||
81 | ||||
82 | // This reference to the type is located entirely at the location of the | |||
83 | // final identifier in the qualified-id. | |||
84 | return CreateParsedType(Type, | |||
85 | Context.getTrivialTypeSourceInfo(Type, NameLoc)); | |||
86 | } | |||
87 | ||||
88 | ParsedType Sema::getConstructorName(IdentifierInfo &II, | |||
89 | SourceLocation NameLoc, | |||
90 | Scope *S, CXXScopeSpec &SS, | |||
91 | bool EnteringContext) { | |||
92 | CXXRecordDecl *CurClass = getCurrentClass(S, &SS); | |||
93 | assert(CurClass && &II == CurClass->getIdentifier() &&(static_cast <bool> (CurClass && &II == CurClass ->getIdentifier() && "not a constructor name") ? void (0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\"" , "clang/lib/Sema/SemaExprCXX.cpp", 94, __extension__ __PRETTY_FUNCTION__ )) | |||
94 | "not a constructor name")(static_cast <bool> (CurClass && &II == CurClass ->getIdentifier() && "not a constructor name") ? void (0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\"" , "clang/lib/Sema/SemaExprCXX.cpp", 94, __extension__ __PRETTY_FUNCTION__ )); | |||
95 | ||||
96 | // When naming a constructor as a member of a dependent context (eg, in a | |||
97 | // friend declaration or an inherited constructor declaration), form an | |||
98 | // unresolved "typename" type. | |||
99 | if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) { | |||
100 | QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II); | |||
101 | return ParsedType::make(T); | |||
102 | } | |||
103 | ||||
104 | if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass)) | |||
105 | return ParsedType(); | |||
106 | ||||
107 | // Find the injected-class-name declaration. Note that we make no attempt to | |||
108 | // diagnose cases where the injected-class-name is shadowed: the only | |||
109 | // declaration that can validly shadow the injected-class-name is a | |||
110 | // non-static data member, and if the class contains both a non-static data | |||
111 | // member and a constructor then it is ill-formed (we check that in | |||
112 | // CheckCompletedCXXClass). | |||
113 | CXXRecordDecl *InjectedClassName = nullptr; | |||
114 | for (NamedDecl *ND : CurClass->lookup(&II)) { | |||
115 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | |||
116 | if (RD && RD->isInjectedClassName()) { | |||
117 | InjectedClassName = RD; | |||
118 | break; | |||
119 | } | |||
120 | } | |||
121 | if (!InjectedClassName) { | |||
122 | if (!CurClass->isInvalidDecl()) { | |||
123 | // FIXME: RequireCompleteDeclContext doesn't check dependent contexts | |||
124 | // properly. Work around it here for now. | |||
125 | Diag(SS.getLastQualifierNameLoc(), | |||
126 | diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange(); | |||
127 | } | |||
128 | return ParsedType(); | |||
129 | } | |||
130 | ||||
131 | QualType T = Context.getTypeDeclType(InjectedClassName); | |||
132 | DiagnoseUseOfDecl(InjectedClassName, NameLoc); | |||
133 | MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false); | |||
134 | ||||
135 | return ParsedType::make(T); | |||
136 | } | |||
137 | ||||
138 | ParsedType Sema::getDestructorName(SourceLocation TildeLoc, | |||
139 | IdentifierInfo &II, | |||
140 | SourceLocation NameLoc, | |||
141 | Scope *S, CXXScopeSpec &SS, | |||
142 | ParsedType ObjectTypePtr, | |||
143 | bool EnteringContext) { | |||
144 | // Determine where to perform name lookup. | |||
145 | ||||
146 | // FIXME: This area of the standard is very messy, and the current | |||
147 | // wording is rather unclear about which scopes we search for the | |||
148 | // destructor name; see core issues 399 and 555. Issue 399 in | |||
149 | // particular shows where the current description of destructor name | |||
150 | // lookup is completely out of line with existing practice, e.g., | |||
151 | // this appears to be ill-formed: | |||
152 | // | |||
153 | // namespace N { | |||
154 | // template <typename T> struct S { | |||
155 | // ~S(); | |||
156 | // }; | |||
157 | // } | |||
158 | // | |||
159 | // void f(N::S<int>* s) { | |||
160 | // s->N::S<int>::~S(); | |||
161 | // } | |||
162 | // | |||
163 | // See also PR6358 and PR6359. | |||
164 | // | |||
165 | // For now, we accept all the cases in which the name given could plausibly | |||
166 | // be interpreted as a correct destructor name, issuing off-by-default | |||
167 | // extension diagnostics on the cases that don't strictly conform to the | |||
168 | // C++20 rules. This basically means we always consider looking in the | |||
169 | // nested-name-specifier prefix, the complete nested-name-specifier, and | |||
170 | // the scope, and accept if we find the expected type in any of the three | |||
171 | // places. | |||
172 | ||||
173 | if (SS.isInvalid()) | |||
174 | return nullptr; | |||
175 | ||||
176 | // Whether we've failed with a diagnostic already. | |||
177 | bool Failed = false; | |||
178 | ||||
179 | llvm::SmallVector<NamedDecl*, 8> FoundDecls; | |||
180 | llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet; | |||
181 | ||||
182 | // If we have an object type, it's because we are in a | |||
183 | // pseudo-destructor-expression or a member access expression, and | |||
184 | // we know what type we're looking for. | |||
185 | QualType SearchType = | |||
186 | ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType(); | |||
187 | ||||
188 | auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType { | |||
189 | auto IsAcceptableResult = [&](NamedDecl *D) -> bool { | |||
190 | auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl()); | |||
191 | if (!Type) | |||
192 | return false; | |||
193 | ||||
194 | if (SearchType.isNull() || SearchType->isDependentType()) | |||
195 | return true; | |||
196 | ||||
197 | QualType T = Context.getTypeDeclType(Type); | |||
198 | return Context.hasSameUnqualifiedType(T, SearchType); | |||
199 | }; | |||
200 | ||||
201 | unsigned NumAcceptableResults = 0; | |||
202 | for (NamedDecl *D : Found) { | |||
203 | if (IsAcceptableResult(D)) | |||
204 | ++NumAcceptableResults; | |||
205 | ||||
206 | // Don't list a class twice in the lookup failure diagnostic if it's | |||
207 | // found by both its injected-class-name and by the name in the enclosing | |||
208 | // scope. | |||
209 | if (auto *RD = dyn_cast<CXXRecordDecl>(D)) | |||
210 | if (RD->isInjectedClassName()) | |||
211 | D = cast<NamedDecl>(RD->getParent()); | |||
212 | ||||
213 | if (FoundDeclSet.insert(D).second) | |||
214 | FoundDecls.push_back(D); | |||
215 | } | |||
216 | ||||
217 | // As an extension, attempt to "fix" an ambiguity by erasing all non-type | |||
218 | // results, and all non-matching results if we have a search type. It's not | |||
219 | // clear what the right behavior is if destructor lookup hits an ambiguity, | |||
220 | // but other compilers do generally accept at least some kinds of | |||
221 | // ambiguity. | |||
222 | if (Found.isAmbiguous() && NumAcceptableResults == 1) { | |||
223 | Diag(NameLoc, diag::ext_dtor_name_ambiguous); | |||
224 | LookupResult::Filter F = Found.makeFilter(); | |||
225 | while (F.hasNext()) { | |||
226 | NamedDecl *D = F.next(); | |||
227 | if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl())) | |||
228 | Diag(D->getLocation(), diag::note_destructor_type_here) | |||
229 | << Context.getTypeDeclType(TD); | |||
230 | else | |||
231 | Diag(D->getLocation(), diag::note_destructor_nontype_here); | |||
232 | ||||
233 | if (!IsAcceptableResult(D)) | |||
234 | F.erase(); | |||
235 | } | |||
236 | F.done(); | |||
237 | } | |||
238 | ||||
239 | if (Found.isAmbiguous()) | |||
240 | Failed = true; | |||
241 | ||||
242 | if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { | |||
243 | if (IsAcceptableResult(Type)) { | |||
244 | QualType T = Context.getTypeDeclType(Type); | |||
245 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); | |||
246 | return CreateParsedType(Context.getElaboratedType(ETK_None, nullptr, T), | |||
247 | Context.getTrivialTypeSourceInfo(T, NameLoc)); | |||
248 | } | |||
249 | } | |||
250 | ||||
251 | return nullptr; | |||
252 | }; | |||
253 | ||||
254 | bool IsDependent = false; | |||
255 | ||||
256 | auto LookupInObjectType = [&]() -> ParsedType { | |||
257 | if (Failed || SearchType.isNull()) | |||
258 | return nullptr; | |||
259 | ||||
260 | IsDependent |= SearchType->isDependentType(); | |||
261 | ||||
262 | LookupResult Found(*this, &II, NameLoc, LookupDestructorName); | |||
263 | DeclContext *LookupCtx = computeDeclContext(SearchType); | |||
264 | if (!LookupCtx) | |||
265 | return nullptr; | |||
266 | LookupQualifiedName(Found, LookupCtx); | |||
267 | return CheckLookupResult(Found); | |||
268 | }; | |||
269 | ||||
270 | auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType { | |||
271 | if (Failed) | |||
272 | return nullptr; | |||
273 | ||||
274 | IsDependent |= isDependentScopeSpecifier(LookupSS); | |||
275 | DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext); | |||
276 | if (!LookupCtx) | |||
277 | return nullptr; | |||
278 | ||||
279 | LookupResult Found(*this, &II, NameLoc, LookupDestructorName); | |||
280 | if (RequireCompleteDeclContext(LookupSS, LookupCtx)) { | |||
281 | Failed = true; | |||
282 | return nullptr; | |||
283 | } | |||
284 | LookupQualifiedName(Found, LookupCtx); | |||
285 | return CheckLookupResult(Found); | |||
286 | }; | |||
287 | ||||
288 | auto LookupInScope = [&]() -> ParsedType { | |||
289 | if (Failed || !S) | |||
290 | return nullptr; | |||
291 | ||||
292 | LookupResult Found(*this, &II, NameLoc, LookupDestructorName); | |||
293 | LookupName(Found, S); | |||
294 | return CheckLookupResult(Found); | |||
295 | }; | |||
296 | ||||
297 | // C++2a [basic.lookup.qual]p6: | |||
298 | // In a qualified-id of the form | |||
299 | // | |||
300 | // nested-name-specifier[opt] type-name :: ~ type-name | |||
301 | // | |||
302 | // the second type-name is looked up in the same scope as the first. | |||
303 | // | |||
304 | // We interpret this as meaning that if you do a dual-scope lookup for the | |||
305 | // first name, you also do a dual-scope lookup for the second name, per | |||
306 | // C++ [basic.lookup.classref]p4: | |||
307 | // | |||
308 | // If the id-expression in a class member access is a qualified-id of the | |||
309 | // form | |||
310 | // | |||
311 | // class-name-or-namespace-name :: ... | |||
312 | // | |||
313 | // the class-name-or-namespace-name following the . or -> is first looked | |||
314 | // up in the class of the object expression and the name, if found, is used. | |||
315 | // Otherwise, it is looked up in the context of the entire | |||
316 | // postfix-expression. | |||
317 | // | |||
318 | // This looks in the same scopes as for an unqualified destructor name: | |||
319 | // | |||
320 | // C++ [basic.lookup.classref]p3: | |||
321 | // If the unqualified-id is ~ type-name, the type-name is looked up | |||
322 | // in the context of the entire postfix-expression. If the type T | |||
323 | // of the object expression is of a class type C, the type-name is | |||
324 | // also looked up in the scope of class C. At least one of the | |||
325 | // lookups shall find a name that refers to cv T. | |||
326 | // | |||
327 | // FIXME: The intent is unclear here. Should type-name::~type-name look in | |||
328 | // the scope anyway if it finds a non-matching name declared in the class? | |||
329 | // If both lookups succeed and find a dependent result, which result should | |||
330 | // we retain? (Same question for p->~type-name().) | |||
331 | ||||
332 | if (NestedNameSpecifier *Prefix = | |||
333 | SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) { | |||
334 | // This is | |||
335 | // | |||
336 | // nested-name-specifier type-name :: ~ type-name | |||
337 | // | |||
338 | // Look for the second type-name in the nested-name-specifier. | |||
339 | CXXScopeSpec PrefixSS; | |||
340 | PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); | |||
341 | if (ParsedType T = LookupInNestedNameSpec(PrefixSS)) | |||
342 | return T; | |||
343 | } else { | |||
344 | // This is one of | |||
345 | // | |||
346 | // type-name :: ~ type-name | |||
347 | // ~ type-name | |||
348 | // | |||
349 | // Look in the scope and (if any) the object type. | |||
350 | if (ParsedType T = LookupInScope()) | |||
351 | return T; | |||
352 | if (ParsedType T = LookupInObjectType()) | |||
353 | return T; | |||
354 | } | |||
355 | ||||
356 | if (Failed) | |||
357 | return nullptr; | |||
358 | ||||
359 | if (IsDependent) { | |||
360 | // We didn't find our type, but that's OK: it's dependent anyway. | |||
361 | ||||
362 | // FIXME: What if we have no nested-name-specifier? | |||
363 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), | |||
364 | SS.getWithLocInContext(Context), | |||
365 | II, NameLoc); | |||
366 | return ParsedType::make(T); | |||
367 | } | |||
368 | ||||
369 | // The remaining cases are all non-standard extensions imitating the behavior | |||
370 | // of various other compilers. | |||
371 | unsigned NumNonExtensionDecls = FoundDecls.size(); | |||
372 | ||||
373 | if (SS.isSet()) { | |||
374 | // For compatibility with older broken C++ rules and existing code, | |||
375 | // | |||
376 | // nested-name-specifier :: ~ type-name | |||
377 | // | |||
378 | // also looks for type-name within the nested-name-specifier. | |||
379 | if (ParsedType T = LookupInNestedNameSpec(SS)) { | |||
380 | Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope) | |||
381 | << SS.getRange() | |||
382 | << FixItHint::CreateInsertion(SS.getEndLoc(), | |||
383 | ("::" + II.getName()).str()); | |||
384 | return T; | |||
385 | } | |||
386 | ||||
387 | // For compatibility with other compilers and older versions of Clang, | |||
388 | // | |||
389 | // nested-name-specifier type-name :: ~ type-name | |||
390 | // | |||
391 | // also looks for type-name in the scope. Unfortunately, we can't | |||
392 | // reasonably apply this fallback for dependent nested-name-specifiers. | |||
393 | if (SS.getScopeRep()->getPrefix()) { | |||
394 | if (ParsedType T = LookupInScope()) { | |||
395 | Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope) | |||
396 | << FixItHint::CreateRemoval(SS.getRange()); | |||
397 | Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here) | |||
398 | << GetTypeFromParser(T); | |||
399 | return T; | |||
400 | } | |||
401 | } | |||
402 | } | |||
403 | ||||
404 | // We didn't find anything matching; tell the user what we did find (if | |||
405 | // anything). | |||
406 | ||||
407 | // Don't tell the user about declarations we shouldn't have found. | |||
408 | FoundDecls.resize(NumNonExtensionDecls); | |||
409 | ||||
410 | // List types before non-types. | |||
411 | std::stable_sort(FoundDecls.begin(), FoundDecls.end(), | |||
412 | [](NamedDecl *A, NamedDecl *B) { | |||
413 | return isa<TypeDecl>(A->getUnderlyingDecl()) > | |||
414 | isa<TypeDecl>(B->getUnderlyingDecl()); | |||
415 | }); | |||
416 | ||||
417 | // Suggest a fixit to properly name the destroyed type. | |||
418 | auto MakeFixItHint = [&]{ | |||
419 | const CXXRecordDecl *Destroyed = nullptr; | |||
420 | // FIXME: If we have a scope specifier, suggest its last component? | |||
421 | if (!SearchType.isNull()) | |||
422 | Destroyed = SearchType->getAsCXXRecordDecl(); | |||
423 | else if (S) | |||
424 | Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity()); | |||
425 | if (Destroyed) | |||
426 | return FixItHint::CreateReplacement(SourceRange(NameLoc), | |||
427 | Destroyed->getNameAsString()); | |||
428 | return FixItHint(); | |||
429 | }; | |||
430 | ||||
431 | if (FoundDecls.empty()) { | |||
432 | // FIXME: Attempt typo-correction? | |||
433 | Diag(NameLoc, diag::err_undeclared_destructor_name) | |||
434 | << &II << MakeFixItHint(); | |||
435 | } else if (!SearchType.isNull() && FoundDecls.size() == 1) { | |||
436 | if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) { | |||
437 | assert(!SearchType.isNull() &&(static_cast <bool> (!SearchType.isNull() && "should only reject a type result if we have a search type" ) ? void (0) : __assert_fail ("!SearchType.isNull() && \"should only reject a type result if we have a search type\"" , "clang/lib/Sema/SemaExprCXX.cpp", 438, __extension__ __PRETTY_FUNCTION__ )) | |||
438 | "should only reject a type result if we have a search type")(static_cast <bool> (!SearchType.isNull() && "should only reject a type result if we have a search type" ) ? void (0) : __assert_fail ("!SearchType.isNull() && \"should only reject a type result if we have a search type\"" , "clang/lib/Sema/SemaExprCXX.cpp", 438, __extension__ __PRETTY_FUNCTION__ )); | |||
439 | QualType T = Context.getTypeDeclType(TD); | |||
440 | Diag(NameLoc, diag::err_destructor_expr_type_mismatch) | |||
441 | << T << SearchType << MakeFixItHint(); | |||
442 | } else { | |||
443 | Diag(NameLoc, diag::err_destructor_expr_nontype) | |||
444 | << &II << MakeFixItHint(); | |||
445 | } | |||
446 | } else { | |||
447 | Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype | |||
448 | : diag::err_destructor_expr_mismatch) | |||
449 | << &II << SearchType << MakeFixItHint(); | |||
450 | } | |||
451 | ||||
452 | for (NamedDecl *FoundD : FoundDecls) { | |||
453 | if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl())) | |||
454 | Diag(FoundD->getLocation(), diag::note_destructor_type_here) | |||
455 | << Context.getTypeDeclType(TD); | |||
456 | else | |||
457 | Diag(FoundD->getLocation(), diag::note_destructor_nontype_here) | |||
458 | << FoundD; | |||
459 | } | |||
460 | ||||
461 | return nullptr; | |||
462 | } | |||
463 | ||||
464 | ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS, | |||
465 | ParsedType ObjectType) { | |||
466 | if (DS.getTypeSpecType() == DeclSpec::TST_error) | |||
467 | return nullptr; | |||
468 | ||||
469 | if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { | |||
470 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); | |||
471 | return nullptr; | |||
472 | } | |||
473 | ||||
474 | assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_decltype && "unexpected type in getDestructorType" ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\"" , "clang/lib/Sema/SemaExprCXX.cpp", 475, __extension__ __PRETTY_FUNCTION__ )) | |||
475 | "unexpected type in getDestructorType")(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_decltype && "unexpected type in getDestructorType" ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\"" , "clang/lib/Sema/SemaExprCXX.cpp", 475, __extension__ __PRETTY_FUNCTION__ )); | |||
476 | QualType T = BuildDecltypeType(DS.getRepAsExpr()); | |||
477 | ||||
478 | // If we know the type of the object, check that the correct destructor | |||
479 | // type was named now; we can give better diagnostics this way. | |||
480 | QualType SearchType = GetTypeFromParser(ObjectType); | |||
481 | if (!SearchType.isNull() && !SearchType->isDependentType() && | |||
482 | !Context.hasSameUnqualifiedType(T, SearchType)) { | |||
483 | Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) | |||
484 | << T << SearchType; | |||
485 | return nullptr; | |||
486 | } | |||
487 | ||||
488 | return ParsedType::make(T); | |||
489 | } | |||
490 | ||||
491 | bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, | |||
492 | const UnqualifiedId &Name, bool IsUDSuffix) { | |||
493 | assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId)(static_cast <bool> (Name.getKind() == UnqualifiedIdKind ::IK_LiteralOperatorId) ? void (0) : __assert_fail ("Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId" , "clang/lib/Sema/SemaExprCXX.cpp", 493, __extension__ __PRETTY_FUNCTION__ )); | |||
494 | if (!IsUDSuffix) { | |||
495 | // [over.literal] p8 | |||
496 | // | |||
497 | // double operator""_Bq(long double); // OK: not a reserved identifier | |||
498 | // double operator"" _Bq(long double); // ill-formed, no diagnostic required | |||
499 | IdentifierInfo *II = Name.Identifier; | |||
500 | ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts()); | |||
501 | SourceLocation Loc = Name.getEndLoc(); | |||
502 | if (isReservedInAllContexts(Status) && | |||
503 | !PP.getSourceManager().isInSystemHeader(Loc)) { | |||
504 | Diag(Loc, diag::warn_reserved_extern_symbol) | |||
505 | << II << static_cast<int>(Status) | |||
506 | << FixItHint::CreateReplacement( | |||
507 | Name.getSourceRange(), | |||
508 | (StringRef("operator\"\"") + II->getName()).str()); | |||
509 | } | |||
510 | } | |||
511 | ||||
512 | if (!SS.isValid()) | |||
513 | return false; | |||
514 | ||||
515 | switch (SS.getScopeRep()->getKind()) { | |||
516 | case NestedNameSpecifier::Identifier: | |||
517 | case NestedNameSpecifier::TypeSpec: | |||
518 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
519 | // Per C++11 [over.literal]p2, literal operators can only be declared at | |||
520 | // namespace scope. Therefore, this unqualified-id cannot name anything. | |||
521 | // Reject it early, because we have no AST representation for this in the | |||
522 | // case where the scope is dependent. | |||
523 | Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace) | |||
524 | << SS.getScopeRep(); | |||
525 | return true; | |||
526 | ||||
527 | case NestedNameSpecifier::Global: | |||
528 | case NestedNameSpecifier::Super: | |||
529 | case NestedNameSpecifier::Namespace: | |||
530 | case NestedNameSpecifier::NamespaceAlias: | |||
531 | return false; | |||
532 | } | |||
533 | ||||
534 | llvm_unreachable("unknown nested name specifier kind")::llvm::llvm_unreachable_internal("unknown nested name specifier kind" , "clang/lib/Sema/SemaExprCXX.cpp", 534); | |||
535 | } | |||
536 | ||||
537 | /// Build a C++ typeid expression with a type operand. | |||
538 | ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, | |||
539 | SourceLocation TypeidLoc, | |||
540 | TypeSourceInfo *Operand, | |||
541 | SourceLocation RParenLoc) { | |||
542 | // C++ [expr.typeid]p4: | |||
543 | // The top-level cv-qualifiers of the lvalue expression or the type-id | |||
544 | // that is the operand of typeid are always ignored. | |||
545 | // If the type of the type-id is a class type or a reference to a class | |||
546 | // type, the class shall be completely-defined. | |||
547 | Qualifiers Quals; | |||
548 | QualType T | |||
549 | = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), | |||
550 | Quals); | |||
551 | if (T->getAs<RecordType>() && | |||
552 | RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) | |||
553 | return ExprError(); | |||
554 | ||||
555 | if (T->isVariablyModifiedType()) | |||
556 | return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T); | |||
557 | ||||
558 | if (CheckQualifiedFunctionForTypeId(T, TypeidLoc)) | |||
559 | return ExprError(); | |||
560 | ||||
561 | return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, | |||
562 | SourceRange(TypeidLoc, RParenLoc)); | |||
563 | } | |||
564 | ||||
565 | /// Build a C++ typeid expression with an expression operand. | |||
566 | ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, | |||
567 | SourceLocation TypeidLoc, | |||
568 | Expr *E, | |||
569 | SourceLocation RParenLoc) { | |||
570 | bool WasEvaluated = false; | |||
571 | if (E && !E->isTypeDependent()) { | |||
572 | if (E->hasPlaceholderType()) { | |||
573 | ExprResult result = CheckPlaceholderExpr(E); | |||
574 | if (result.isInvalid()) return ExprError(); | |||
575 | E = result.get(); | |||
576 | } | |||
577 | ||||
578 | QualType T = E->getType(); | |||
579 | if (const RecordType *RecordT = T->getAs<RecordType>()) { | |||
580 | CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); | |||
581 | // C++ [expr.typeid]p3: | |||
582 | // [...] If the type of the expression is a class type, the class | |||
583 | // shall be completely-defined. | |||
584 | if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) | |||
585 | return ExprError(); | |||
586 | ||||
587 | // C++ [expr.typeid]p3: | |||
588 | // When typeid is applied to an expression other than an glvalue of a | |||
589 | // polymorphic class type [...] [the] expression is an unevaluated | |||
590 | // operand. [...] | |||
591 | if (RecordD->isPolymorphic() && E->isGLValue()) { | |||
592 | if (isUnevaluatedContext()) { | |||
593 | // The operand was processed in unevaluated context, switch the | |||
594 | // context and recheck the subexpression. | |||
595 | ExprResult Result = TransformToPotentiallyEvaluated(E); | |||
596 | if (Result.isInvalid()) | |||
597 | return ExprError(); | |||
598 | E = Result.get(); | |||
599 | } | |||
600 | ||||
601 | // We require a vtable to query the type at run time. | |||
602 | MarkVTableUsed(TypeidLoc, RecordD); | |||
603 | WasEvaluated = true; | |||
604 | } | |||
605 | } | |||
606 | ||||
607 | ExprResult Result = CheckUnevaluatedOperand(E); | |||
608 | if (Result.isInvalid()) | |||
609 | return ExprError(); | |||
610 | E = Result.get(); | |||
611 | ||||
612 | // C++ [expr.typeid]p4: | |||
613 | // [...] If the type of the type-id is a reference to a possibly | |||
614 | // cv-qualified type, the result of the typeid expression refers to a | |||
615 | // std::type_info object representing the cv-unqualified referenced | |||
616 | // type. | |||
617 | Qualifiers Quals; | |||
618 | QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); | |||
619 | if (!Context.hasSameType(T, UnqualT)) { | |||
620 | T = UnqualT; | |||
621 | E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get(); | |||
622 | } | |||
623 | } | |||
624 | ||||
625 | if (E->getType()->isVariablyModifiedType()) | |||
626 | return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) | |||
627 | << E->getType()); | |||
628 | else if (!inTemplateInstantiation() && | |||
629 | E->HasSideEffects(Context, WasEvaluated)) { | |||
630 | // The expression operand for typeid is in an unevaluated expression | |||
631 | // context, so side effects could result in unintended consequences. | |||
632 | Diag(E->getExprLoc(), WasEvaluated | |||
633 | ? diag::warn_side_effects_typeid | |||
634 | : diag::warn_side_effects_unevaluated_context); | |||
635 | } | |||
636 | ||||
637 | return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, | |||
638 | SourceRange(TypeidLoc, RParenLoc)); | |||
639 | } | |||
640 | ||||
641 | /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); | |||
642 | ExprResult | |||
643 | Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, | |||
644 | bool isType, void *TyOrExpr, SourceLocation RParenLoc) { | |||
645 | // typeid is not supported in OpenCL. | |||
646 | if (getLangOpts().OpenCLCPlusPlus) { | |||
647 | return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) | |||
648 | << "typeid"); | |||
649 | } | |||
650 | ||||
651 | // Find the std::type_info type. | |||
652 | if (!getStdNamespace()) | |||
653 | return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); | |||
654 | ||||
655 | if (!CXXTypeInfoDecl) { | |||
656 | IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); | |||
657 | LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); | |||
658 | LookupQualifiedName(R, getStdNamespace()); | |||
659 | CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); | |||
660 | // Microsoft's typeinfo doesn't have type_info in std but in the global | |||
661 | // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. | |||
662 | if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) { | |||
663 | LookupQualifiedName(R, Context.getTranslationUnitDecl()); | |||
664 | CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); | |||
665 | } | |||
666 | if (!CXXTypeInfoDecl) | |||
667 | return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); | |||
668 | } | |||
669 | ||||
670 | if (!getLangOpts().RTTI) { | |||
671 | return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); | |||
672 | } | |||
673 | ||||
674 | QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); | |||
675 | ||||
676 | if (isType) { | |||
677 | // The operand is a type; handle it as such. | |||
678 | TypeSourceInfo *TInfo = nullptr; | |||
679 | QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), | |||
680 | &TInfo); | |||
681 | if (T.isNull()) | |||
682 | return ExprError(); | |||
683 | ||||
684 | if (!TInfo) | |||
685 | TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); | |||
686 | ||||
687 | return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); | |||
688 | } | |||
689 | ||||
690 | // The operand is an expression. | |||
691 | ExprResult Result = | |||
692 | BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc); | |||
693 | ||||
694 | if (!getLangOpts().RTTIData && !Result.isInvalid()) | |||
695 | if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get())) | |||
696 | if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context)) | |||
697 | Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled) | |||
698 | << (getDiagnostics().getDiagnosticOptions().getFormat() == | |||
699 | DiagnosticOptions::MSVC); | |||
700 | return Result; | |||
701 | } | |||
702 | ||||
703 | /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to | |||
704 | /// a single GUID. | |||
705 | static void | |||
706 | getUuidAttrOfType(Sema &SemaRef, QualType QT, | |||
707 | llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { | |||
708 | // Optionally remove one level of pointer, reference or array indirection. | |||
709 | const Type *Ty = QT.getTypePtr(); | |||
710 | if (QT->isPointerType() || QT->isReferenceType()) | |||
711 | Ty = QT->getPointeeType().getTypePtr(); | |||
712 | else if (QT->isArrayType()) | |||
713 | Ty = Ty->getBaseElementTypeUnsafe(); | |||
714 | ||||
715 | const auto *TD = Ty->getAsTagDecl(); | |||
716 | if (!TD) | |||
717 | return; | |||
718 | ||||
719 | if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) { | |||
720 | UuidAttrs.insert(Uuid); | |||
721 | return; | |||
722 | } | |||
723 | ||||
724 | // __uuidof can grab UUIDs from template arguments. | |||
725 | if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) { | |||
726 | const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); | |||
727 | for (const TemplateArgument &TA : TAL.asArray()) { | |||
728 | const UuidAttr *UuidForTA = nullptr; | |||
729 | if (TA.getKind() == TemplateArgument::Type) | |||
730 | getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs); | |||
731 | else if (TA.getKind() == TemplateArgument::Declaration) | |||
732 | getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs); | |||
733 | ||||
734 | if (UuidForTA) | |||
735 | UuidAttrs.insert(UuidForTA); | |||
736 | } | |||
737 | } | |||
738 | } | |||
739 | ||||
740 | /// Build a Microsoft __uuidof expression with a type operand. | |||
741 | ExprResult Sema::BuildCXXUuidof(QualType Type, | |||
742 | SourceLocation TypeidLoc, | |||
743 | TypeSourceInfo *Operand, | |||
744 | SourceLocation RParenLoc) { | |||
745 | MSGuidDecl *Guid = nullptr; | |||
746 | if (!Operand->getType()->isDependentType()) { | |||
747 | llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; | |||
748 | getUuidAttrOfType(*this, Operand->getType(), UuidAttrs); | |||
749 | if (UuidAttrs.empty()) | |||
750 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); | |||
751 | if (UuidAttrs.size() > 1) | |||
752 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); | |||
753 | Guid = UuidAttrs.back()->getGuidDecl(); | |||
754 | } | |||
755 | ||||
756 | return new (Context) | |||
757 | CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc)); | |||
758 | } | |||
759 | ||||
760 | /// Build a Microsoft __uuidof expression with an expression operand. | |||
761 | ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc, | |||
762 | Expr *E, SourceLocation RParenLoc) { | |||
763 | MSGuidDecl *Guid = nullptr; | |||
764 | if (!E->getType()->isDependentType()) { | |||
765 | if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { | |||
766 | // A null pointer results in {00000000-0000-0000-0000-000000000000}. | |||
767 | Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{}); | |||
768 | } else { | |||
769 | llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; | |||
770 | getUuidAttrOfType(*this, E->getType(), UuidAttrs); | |||
771 | if (UuidAttrs.empty()) | |||
772 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); | |||
773 | if (UuidAttrs.size() > 1) | |||
774 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); | |||
775 | Guid = UuidAttrs.back()->getGuidDecl(); | |||
776 | } | |||
777 | } | |||
778 | ||||
779 | return new (Context) | |||
780 | CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc)); | |||
781 | } | |||
782 | ||||
783 | /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); | |||
784 | ExprResult | |||
785 | Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, | |||
786 | bool isType, void *TyOrExpr, SourceLocation RParenLoc) { | |||
787 | QualType GuidType = Context.getMSGuidType(); | |||
788 | GuidType.addConst(); | |||
789 | ||||
790 | if (isType) { | |||
791 | // The operand is a type; handle it as such. | |||
792 | TypeSourceInfo *TInfo = nullptr; | |||
793 | QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), | |||
794 | &TInfo); | |||
795 | if (T.isNull()) | |||
796 | return ExprError(); | |||
797 | ||||
798 | if (!TInfo) | |||
799 | TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); | |||
800 | ||||
801 | return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); | |||
802 | } | |||
803 | ||||
804 | // The operand is an expression. | |||
805 | return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); | |||
806 | } | |||
807 | ||||
808 | /// ActOnCXXBoolLiteral - Parse {true,false} literals. | |||
809 | ExprResult | |||
810 | Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { | |||
811 | assert((Kind == tok::kw_true || Kind == tok::kw_false) &&(static_cast <bool> ((Kind == tok::kw_true || Kind == tok ::kw_false) && "Unknown C++ Boolean value!") ? void ( 0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\"" , "clang/lib/Sema/SemaExprCXX.cpp", 812, __extension__ __PRETTY_FUNCTION__ )) | |||
812 | "Unknown C++ Boolean value!")(static_cast <bool> ((Kind == tok::kw_true || Kind == tok ::kw_false) && "Unknown C++ Boolean value!") ? void ( 0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\"" , "clang/lib/Sema/SemaExprCXX.cpp", 812, __extension__ __PRETTY_FUNCTION__ )); | |||
813 | return new (Context) | |||
814 | CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); | |||
815 | } | |||
816 | ||||
817 | /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. | |||
818 | ExprResult | |||
819 | Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { | |||
820 | return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); | |||
821 | } | |||
822 | ||||
823 | /// ActOnCXXThrow - Parse throw expressions. | |||
824 | ExprResult | |||
825 | Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { | |||
826 | bool IsThrownVarInScope = false; | |||
827 | if (Ex) { | |||
828 | // C++0x [class.copymove]p31: | |||
829 | // When certain criteria are met, an implementation is allowed to omit the | |||
830 | // copy/move construction of a class object [...] | |||
831 | // | |||
832 | // - in a throw-expression, when the operand is the name of a | |||
833 | // non-volatile automatic object (other than a function or catch- | |||
834 | // clause parameter) whose scope does not extend beyond the end of the | |||
835 | // innermost enclosing try-block (if there is one), the copy/move | |||
836 | // operation from the operand to the exception object (15.1) can be | |||
837 | // omitted by constructing the automatic object directly into the | |||
838 | // exception object | |||
839 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) | |||
840 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | |||
841 | if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) { | |||
842 | for( ; S; S = S->getParent()) { | |||
843 | if (S->isDeclScope(Var)) { | |||
844 | IsThrownVarInScope = true; | |||
845 | break; | |||
846 | } | |||
847 | ||||
848 | // FIXME: Many of the scope checks here seem incorrect. | |||
849 | if (S->getFlags() & | |||
850 | (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | | |||
851 | Scope::ObjCMethodScope | Scope::TryScope)) | |||
852 | break; | |||
853 | } | |||
854 | } | |||
855 | } | |||
856 | } | |||
857 | ||||
858 | return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); | |||
859 | } | |||
860 | ||||
861 | ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, | |||
862 | bool IsThrownVarInScope) { | |||
863 | // Don't report an error if 'throw' is used in system headers. | |||
864 | if (!getLangOpts().CXXExceptions && | |||
865 | !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) { | |||
866 | // Delay error emission for the OpenMP device code. | |||
867 | targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw"; | |||
868 | } | |||
869 | ||||
870 | // Exceptions aren't allowed in CUDA device code. | |||
871 | if (getLangOpts().CUDA) | |||
872 | CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions) | |||
873 | << "throw" << CurrentCUDATarget(); | |||
874 | ||||
875 | if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) | |||
876 | Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw"; | |||
877 | ||||
878 | if (Ex && !Ex->isTypeDependent()) { | |||
879 | // Initialize the exception result. This implicitly weeds out | |||
880 | // abstract types or types with inaccessible copy constructors. | |||
881 | ||||
882 | // C++0x [class.copymove]p31: | |||
883 | // When certain criteria are met, an implementation is allowed to omit the | |||
884 | // copy/move construction of a class object [...] | |||
885 | // | |||
886 | // - in a throw-expression, when the operand is the name of a | |||
887 | // non-volatile automatic object (other than a function or | |||
888 | // catch-clause | |||
889 | // parameter) whose scope does not extend beyond the end of the | |||
890 | // innermost enclosing try-block (if there is one), the copy/move | |||
891 | // operation from the operand to the exception object (15.1) can be | |||
892 | // omitted by constructing the automatic object directly into the | |||
893 | // exception object | |||
894 | NamedReturnInfo NRInfo = | |||
895 | IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo(); | |||
896 | ||||
897 | QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType()); | |||
898 | if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex)) | |||
899 | return ExprError(); | |||
900 | ||||
901 | InitializedEntity Entity = | |||
902 | InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy); | |||
903 | ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex); | |||
904 | if (Res.isInvalid()) | |||
905 | return ExprError(); | |||
906 | Ex = Res.get(); | |||
907 | } | |||
908 | ||||
909 | // PPC MMA non-pointer types are not allowed as throw expr types. | |||
910 | if (Ex && Context.getTargetInfo().getTriple().isPPC64()) | |||
911 | CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc()); | |||
912 | ||||
913 | return new (Context) | |||
914 | CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope); | |||
915 | } | |||
916 | ||||
917 | static void | |||
918 | collectPublicBases(CXXRecordDecl *RD, | |||
919 | llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen, | |||
920 | llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases, | |||
921 | llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen, | |||
922 | bool ParentIsPublic) { | |||
923 | for (const CXXBaseSpecifier &BS : RD->bases()) { | |||
924 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); | |||
925 | bool NewSubobject; | |||
926 | // Virtual bases constitute the same subobject. Non-virtual bases are | |||
927 | // always distinct subobjects. | |||
928 | if (BS.isVirtual()) | |||
929 | NewSubobject = VBases.insert(BaseDecl).second; | |||
930 | else | |||
931 | NewSubobject = true; | |||
932 | ||||
933 | if (NewSubobject) | |||
934 | ++SubobjectsSeen[BaseDecl]; | |||
935 | ||||
936 | // Only add subobjects which have public access throughout the entire chain. | |||
937 | bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; | |||
938 | if (PublicPath) | |||
939 | PublicSubobjectsSeen.insert(BaseDecl); | |||
940 | ||||
941 | // Recurse on to each base subobject. | |||
942 | collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, | |||
943 | PublicPath); | |||
944 | } | |||
945 | } | |||
946 | ||||
947 | static void getUnambiguousPublicSubobjects( | |||
948 | CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) { | |||
949 | llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen; | |||
950 | llvm::SmallSet<CXXRecordDecl *, 2> VBases; | |||
951 | llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen; | |||
952 | SubobjectsSeen[RD] = 1; | |||
953 | PublicSubobjectsSeen.insert(RD); | |||
954 | collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen, | |||
955 | /*ParentIsPublic=*/true); | |||
956 | ||||
957 | for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { | |||
958 | // Skip ambiguous objects. | |||
959 | if (SubobjectsSeen[PublicSubobject] > 1) | |||
960 | continue; | |||
961 | ||||
962 | Objects.push_back(PublicSubobject); | |||
963 | } | |||
964 | } | |||
965 | ||||
966 | /// CheckCXXThrowOperand - Validate the operand of a throw. | |||
967 | bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, | |||
968 | QualType ExceptionObjectTy, Expr *E) { | |||
969 | // If the type of the exception would be an incomplete type or a pointer | |||
970 | // to an incomplete type other than (cv) void the program is ill-formed. | |||
971 | QualType Ty = ExceptionObjectTy; | |||
972 | bool isPointer = false; | |||
973 | if (const PointerType* Ptr = Ty->getAs<PointerType>()) { | |||
974 | Ty = Ptr->getPointeeType(); | |||
975 | isPointer = true; | |||
976 | } | |||
977 | if (!isPointer || !Ty->isVoidType()) { | |||
978 | if (RequireCompleteType(ThrowLoc, Ty, | |||
979 | isPointer ? diag::err_throw_incomplete_ptr | |||
980 | : diag::err_throw_incomplete, | |||
981 | E->getSourceRange())) | |||
982 | return true; | |||
983 | ||||
984 | if (!isPointer && Ty->isSizelessType()) { | |||
985 | Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange(); | |||
986 | return true; | |||
987 | } | |||
988 | ||||
989 | if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy, | |||
990 | diag::err_throw_abstract_type, E)) | |||
991 | return true; | |||
992 | } | |||
993 | ||||
994 | // If the exception has class type, we need additional handling. | |||
995 | CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); | |||
996 | if (!RD) | |||
997 | return false; | |||
998 | ||||
999 | // If we are throwing a polymorphic class type or pointer thereof, | |||
1000 | // exception handling will make use of the vtable. | |||
1001 | MarkVTableUsed(ThrowLoc, RD); | |||
1002 | ||||
1003 | // If a pointer is thrown, the referenced object will not be destroyed. | |||
1004 | if (isPointer) | |||
1005 | return false; | |||
1006 | ||||
1007 | // If the class has a destructor, we must be able to call it. | |||
1008 | if (!RD->hasIrrelevantDestructor()) { | |||
1009 | if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { | |||
1010 | MarkFunctionReferenced(E->getExprLoc(), Destructor); | |||
1011 | CheckDestructorAccess(E->getExprLoc(), Destructor, | |||
1012 | PDiag(diag::err_access_dtor_exception) << Ty); | |||
1013 | if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) | |||
1014 | return true; | |||
1015 | } | |||
1016 | } | |||
1017 | ||||
1018 | // The MSVC ABI creates a list of all types which can catch the exception | |||
1019 | // object. This list also references the appropriate copy constructor to call | |||
1020 | // if the object is caught by value and has a non-trivial copy constructor. | |||
1021 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
1022 | // We are only interested in the public, unambiguous bases contained within | |||
1023 | // the exception object. Bases which are ambiguous or otherwise | |||
1024 | // inaccessible are not catchable types. | |||
1025 | llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; | |||
1026 | getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects); | |||
1027 | ||||
1028 | for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { | |||
1029 | // Attempt to lookup the copy constructor. Various pieces of machinery | |||
1030 | // will spring into action, like template instantiation, which means this | |||
1031 | // cannot be a simple walk of the class's decls. Instead, we must perform | |||
1032 | // lookup and overload resolution. | |||
1033 | CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0); | |||
1034 | if (!CD || CD->isDeleted()) | |||
1035 | continue; | |||
1036 | ||||
1037 | // Mark the constructor referenced as it is used by this throw expression. | |||
1038 | MarkFunctionReferenced(E->getExprLoc(), CD); | |||
1039 | ||||
1040 | // Skip this copy constructor if it is trivial, we don't need to record it | |||
1041 | // in the catchable type data. | |||
1042 | if (CD->isTrivial()) | |||
1043 | continue; | |||
1044 | ||||
1045 | // The copy constructor is non-trivial, create a mapping from this class | |||
1046 | // type to this constructor. | |||
1047 | // N.B. The selection of copy constructor is not sensitive to this | |||
1048 | // particular throw-site. Lookup will be performed at the catch-site to | |||
1049 | // ensure that the copy constructor is, in fact, accessible (via | |||
1050 | // friendship or any other means). | |||
1051 | Context.addCopyConstructorForExceptionObject(Subobject, CD); | |||
1052 | ||||
1053 | // We don't keep the instantiated default argument expressions around so | |||
1054 | // we must rebuild them here. | |||
1055 | for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) { | |||
1056 | if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I))) | |||
1057 | return true; | |||
1058 | } | |||
1059 | } | |||
1060 | } | |||
1061 | ||||
1062 | // Under the Itanium C++ ABI, memory for the exception object is allocated by | |||
1063 | // the runtime with no ability for the compiler to request additional | |||
1064 | // alignment. Warn if the exception type requires alignment beyond the minimum | |||
1065 | // guaranteed by the target C++ runtime. | |||
1066 | if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) { | |||
1067 | CharUnits TypeAlign = Context.getTypeAlignInChars(Ty); | |||
1068 | CharUnits ExnObjAlign = Context.getExnObjectAlignment(); | |||
1069 | if (ExnObjAlign < TypeAlign) { | |||
1070 | Diag(ThrowLoc, diag::warn_throw_underaligned_obj); | |||
1071 | Diag(ThrowLoc, diag::note_throw_underaligned_obj) | |||
1072 | << Ty << (unsigned)TypeAlign.getQuantity() | |||
1073 | << (unsigned)ExnObjAlign.getQuantity(); | |||
1074 | } | |||
1075 | } | |||
1076 | ||||
1077 | return false; | |||
1078 | } | |||
1079 | ||||
1080 | static QualType adjustCVQualifiersForCXXThisWithinLambda( | |||
1081 | ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy, | |||
1082 | DeclContext *CurSemaContext, ASTContext &ASTCtx) { | |||
1083 | ||||
1084 | QualType ClassType = ThisTy->getPointeeType(); | |||
1085 | LambdaScopeInfo *CurLSI = nullptr; | |||
1086 | DeclContext *CurDC = CurSemaContext; | |||
1087 | ||||
1088 | // Iterate through the stack of lambdas starting from the innermost lambda to | |||
1089 | // the outermost lambda, checking if '*this' is ever captured by copy - since | |||
1090 | // that could change the cv-qualifiers of the '*this' object. | |||
1091 | // The object referred to by '*this' starts out with the cv-qualifiers of its | |||
1092 | // member function. We then start with the innermost lambda and iterate | |||
1093 | // outward checking to see if any lambda performs a by-copy capture of '*this' | |||
1094 | // - and if so, any nested lambda must respect the 'constness' of that | |||
1095 | // capturing lamdbda's call operator. | |||
1096 | // | |||
1097 | ||||
1098 | // Since the FunctionScopeInfo stack is representative of the lexical | |||
1099 | // nesting of the lambda expressions during initial parsing (and is the best | |||
1100 | // place for querying information about captures about lambdas that are | |||
1101 | // partially processed) and perhaps during instantiation of function templates | |||
1102 | // that contain lambda expressions that need to be transformed BUT not | |||
1103 | // necessarily during instantiation of a nested generic lambda's function call | |||
1104 | // operator (which might even be instantiated at the end of the TU) - at which | |||
1105 | // time the DeclContext tree is mature enough to query capture information | |||
1106 | // reliably - we use a two pronged approach to walk through all the lexically | |||
1107 | // enclosing lambda expressions: | |||
1108 | // | |||
1109 | // 1) Climb down the FunctionScopeInfo stack as long as each item represents | |||
1110 | // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically | |||
1111 | // enclosed by the call-operator of the LSI below it on the stack (while | |||
1112 | // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on | |||
1113 | // the stack represents the innermost lambda. | |||
1114 | // | |||
1115 | // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext | |||
1116 | // represents a lambda's call operator. If it does, we must be instantiating | |||
1117 | // a generic lambda's call operator (represented by the Current LSI, and | |||
1118 | // should be the only scenario where an inconsistency between the LSI and the | |||
1119 | // DeclContext should occur), so climb out the DeclContexts if they | |||
1120 | // represent lambdas, while querying the corresponding closure types | |||
1121 | // regarding capture information. | |||
1122 | ||||
1123 | // 1) Climb down the function scope info stack. | |||
1124 | for (int I = FunctionScopes.size(); | |||
1125 | I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) && | |||
1126 | (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() == | |||
1127 | cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator); | |||
1128 | CurDC = getLambdaAwareParentOfDeclContext(CurDC)) { | |||
1129 | CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]); | |||
1130 | ||||
1131 | if (!CurLSI->isCXXThisCaptured()) | |||
1132 | continue; | |||
1133 | ||||
1134 | auto C = CurLSI->getCXXThisCapture(); | |||
1135 | ||||
1136 | if (C.isCopyCapture()) { | |||
1137 | ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); | |||
1138 | if (CurLSI->CallOperator->isConst()) | |||
1139 | ClassType.addConst(); | |||
1140 | return ASTCtx.getPointerType(ClassType); | |||
1141 | } | |||
1142 | } | |||
1143 | ||||
1144 | // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which | |||
1145 | // can happen during instantiation of its nested generic lambda call | |||
1146 | // operator); 2. if we're in a lambda scope (lambda body). | |||
1147 | if (CurLSI && isLambdaCallOperator(CurDC)) { | |||
1148 | assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&(static_cast <bool> (isGenericLambdaCallOperatorSpecialization (CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1152, __extension__ __PRETTY_FUNCTION__ )) | |||
1149 | "While computing 'this' capture-type for a generic lambda, when we "(static_cast <bool> (isGenericLambdaCallOperatorSpecialization (CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1152, __extension__ __PRETTY_FUNCTION__ )) | |||
1150 | "run out of enclosing LSI's, yet the enclosing DC is a "(static_cast <bool> (isGenericLambdaCallOperatorSpecialization (CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1152, __extension__ __PRETTY_FUNCTION__ )) | |||
1151 | "lambda-call-operator we must be (i.e. Current LSI) in a generic "(static_cast <bool> (isGenericLambdaCallOperatorSpecialization (CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1152, __extension__ __PRETTY_FUNCTION__ )) | |||
1152 | "lambda call oeprator")(static_cast <bool> (isGenericLambdaCallOperatorSpecialization (CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1152, __extension__ __PRETTY_FUNCTION__ )); | |||
1153 | assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator))(static_cast <bool> (CurDC == getLambdaAwareParentOfDeclContext (CurLSI->CallOperator)) ? void (0) : __assert_fail ("CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)" , "clang/lib/Sema/SemaExprCXX.cpp", 1153, __extension__ __PRETTY_FUNCTION__ )); | |||
1154 | ||||
1155 | auto IsThisCaptured = | |||
1156 | [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) { | |||
1157 | IsConst = false; | |||
1158 | IsByCopy = false; | |||
1159 | for (auto &&C : Closure->captures()) { | |||
1160 | if (C.capturesThis()) { | |||
1161 | if (C.getCaptureKind() == LCK_StarThis) | |||
1162 | IsByCopy = true; | |||
1163 | if (Closure->getLambdaCallOperator()->isConst()) | |||
1164 | IsConst = true; | |||
1165 | return true; | |||
1166 | } | |||
1167 | } | |||
1168 | return false; | |||
1169 | }; | |||
1170 | ||||
1171 | bool IsByCopyCapture = false; | |||
1172 | bool IsConstCapture = false; | |||
1173 | CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent()); | |||
1174 | while (Closure && | |||
1175 | IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) { | |||
1176 | if (IsByCopyCapture) { | |||
1177 | ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); | |||
1178 | if (IsConstCapture) | |||
1179 | ClassType.addConst(); | |||
1180 | return ASTCtx.getPointerType(ClassType); | |||
1181 | } | |||
1182 | Closure = isLambdaCallOperator(Closure->getParent()) | |||
1183 | ? cast<CXXRecordDecl>(Closure->getParent()->getParent()) | |||
1184 | : nullptr; | |||
1185 | } | |||
1186 | } | |||
1187 | return ASTCtx.getPointerType(ClassType); | |||
1188 | } | |||
1189 | ||||
1190 | QualType Sema::getCurrentThisType() { | |||
1191 | DeclContext *DC = getFunctionLevelDeclContext(); | |||
1192 | QualType ThisTy = CXXThisTypeOverride; | |||
1193 | ||||
1194 | if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { | |||
1195 | if (method && method->isInstance()) | |||
1196 | ThisTy = method->getThisType(); | |||
1197 | } | |||
1198 | ||||
1199 | if (ThisTy.isNull() && isLambdaCallOperator(CurContext) && | |||
1200 | inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) { | |||
1201 | ||||
1202 | // This is a lambda call operator that is being instantiated as a default | |||
1203 | // initializer. DC must point to the enclosing class type, so we can recover | |||
1204 | // the 'this' type from it. | |||
1205 | QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC)); | |||
1206 | // There are no cv-qualifiers for 'this' within default initializers, | |||
1207 | // per [expr.prim.general]p4. | |||
1208 | ThisTy = Context.getPointerType(ClassTy); | |||
1209 | } | |||
1210 | ||||
1211 | // If we are within a lambda's call operator, the cv-qualifiers of 'this' | |||
1212 | // might need to be adjusted if the lambda or any of its enclosing lambda's | |||
1213 | // captures '*this' by copy. | |||
1214 | if (!ThisTy.isNull() && isLambdaCallOperator(CurContext)) | |||
1215 | return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, | |||
1216 | CurContext, Context); | |||
1217 | return ThisTy; | |||
1218 | } | |||
1219 | ||||
1220 | Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, | |||
1221 | Decl *ContextDecl, | |||
1222 | Qualifiers CXXThisTypeQuals, | |||
1223 | bool Enabled) | |||
1224 | : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) | |||
1225 | { | |||
1226 | if (!Enabled || !ContextDecl) | |||
1227 | return; | |||
1228 | ||||
1229 | CXXRecordDecl *Record = nullptr; | |||
1230 | if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) | |||
1231 | Record = Template->getTemplatedDecl(); | |||
1232 | else | |||
1233 | Record = cast<CXXRecordDecl>(ContextDecl); | |||
1234 | ||||
1235 | QualType T = S.Context.getRecordType(Record); | |||
1236 | T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals); | |||
1237 | ||||
1238 | S.CXXThisTypeOverride = S.Context.getPointerType(T); | |||
1239 | ||||
1240 | this->Enabled = true; | |||
1241 | } | |||
1242 | ||||
1243 | ||||
1244 | Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { | |||
1245 | if (Enabled) { | |||
1246 | S.CXXThisTypeOverride = OldCXXThisTypeOverride; | |||
1247 | } | |||
1248 | } | |||
1249 | ||||
1250 | static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) { | |||
1251 | SourceLocation DiagLoc = LSI->IntroducerRange.getEnd(); | |||
1252 | assert(!LSI->isCXXThisCaptured())(static_cast <bool> (!LSI->isCXXThisCaptured()) ? void (0) : __assert_fail ("!LSI->isCXXThisCaptured()", "clang/lib/Sema/SemaExprCXX.cpp" , 1252, __extension__ __PRETTY_FUNCTION__)); | |||
1253 | // [=, this] {}; // until C++20: Error: this when = is the default | |||
1254 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval && | |||
1255 | !Sema.getLangOpts().CPlusPlus20) | |||
1256 | return; | |||
1257 | Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit) | |||
1258 | << FixItHint::CreateInsertion( | |||
1259 | DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this"); | |||
1260 | } | |||
1261 | ||||
1262 | bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, | |||
1263 | bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, | |||
1264 | const bool ByCopy) { | |||
1265 | // We don't need to capture this in an unevaluated context. | |||
1266 | if (isUnevaluatedContext() && !Explicit) | |||
1267 | return true; | |||
1268 | ||||
1269 | assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value")(static_cast <bool> ((!ByCopy || Explicit) && "cannot implicitly capture *this by value" ) ? void (0) : __assert_fail ("(!ByCopy || Explicit) && \"cannot implicitly capture *this by value\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1269, __extension__ __PRETTY_FUNCTION__ )); | |||
1270 | ||||
1271 | const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt | |||
1272 | ? *FunctionScopeIndexToStopAt | |||
1273 | : FunctionScopes.size() - 1; | |||
1274 | ||||
1275 | // Check that we can capture the *enclosing object* (referred to by '*this') | |||
1276 | // by the capturing-entity/closure (lambda/block/etc) at | |||
1277 | // MaxFunctionScopesIndex-deep on the FunctionScopes stack. | |||
1278 | ||||
1279 | // Note: The *enclosing object* can only be captured by-value by a | |||
1280 | // closure that is a lambda, using the explicit notation: | |||
1281 | // [*this] { ... }. | |||
1282 | // Every other capture of the *enclosing object* results in its by-reference | |||
1283 | // capture. | |||
1284 | ||||
1285 | // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes | |||
1286 | // stack), we can capture the *enclosing object* only if: | |||
1287 | // - 'L' has an explicit byref or byval capture of the *enclosing object* | |||
1288 | // - or, 'L' has an implicit capture. | |||
1289 | // AND | |||
1290 | // -- there is no enclosing closure | |||
1291 | // -- or, there is some enclosing closure 'E' that has already captured the | |||
1292 | // *enclosing object*, and every intervening closure (if any) between 'E' | |||
1293 | // and 'L' can implicitly capture the *enclosing object*. | |||
1294 | // -- or, every enclosing closure can implicitly capture the | |||
1295 | // *enclosing object* | |||
1296 | ||||
1297 | ||||
1298 | unsigned NumCapturingClosures = 0; | |||
1299 | for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) { | |||
1300 | if (CapturingScopeInfo *CSI = | |||
1301 | dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { | |||
1302 | if (CSI->CXXThisCaptureIndex != 0) { | |||
1303 | // 'this' is already being captured; there isn't anything more to do. | |||
1304 | CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose); | |||
1305 | break; | |||
1306 | } | |||
1307 | LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI); | |||
1308 | if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { | |||
1309 | // This context can't implicitly capture 'this'; fail out. | |||
1310 | if (BuildAndDiagnose) { | |||
1311 | Diag(Loc, diag::err_this_capture) | |||
1312 | << (Explicit && idx == MaxFunctionScopesIndex); | |||
1313 | if (!Explicit) | |||
1314 | buildLambdaThisCaptureFixit(*this, LSI); | |||
1315 | } | |||
1316 | return true; | |||
1317 | } | |||
1318 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || | |||
1319 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || | |||
1320 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || | |||
1321 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || | |||
1322 | (Explicit && idx == MaxFunctionScopesIndex)) { | |||
1323 | // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first | |||
1324 | // iteration through can be an explicit capture, all enclosing closures, | |||
1325 | // if any, must perform implicit captures. | |||
1326 | ||||
1327 | // This closure can capture 'this'; continue looking upwards. | |||
1328 | NumCapturingClosures++; | |||
1329 | continue; | |||
1330 | } | |||
1331 | // This context can't implicitly capture 'this'; fail out. | |||
1332 | if (BuildAndDiagnose) | |||
1333 | Diag(Loc, diag::err_this_capture) | |||
1334 | << (Explicit && idx == MaxFunctionScopesIndex); | |||
1335 | ||||
1336 | if (!Explicit) | |||
1337 | buildLambdaThisCaptureFixit(*this, LSI); | |||
1338 | return true; | |||
1339 | } | |||
1340 | break; | |||
1341 | } | |||
1342 | if (!BuildAndDiagnose) return false; | |||
1343 | ||||
1344 | // If we got here, then the closure at MaxFunctionScopesIndex on the | |||
1345 | // FunctionScopes stack, can capture the *enclosing object*, so capture it | |||
1346 | // (including implicit by-reference captures in any enclosing closures). | |||
1347 | ||||
1348 | // In the loop below, respect the ByCopy flag only for the closure requesting | |||
1349 | // the capture (i.e. first iteration through the loop below). Ignore it for | |||
1350 | // all enclosing closure's up to NumCapturingClosures (since they must be | |||
1351 | // implicitly capturing the *enclosing object* by reference (see loop | |||
1352 | // above)). | |||
1353 | assert((!ByCopy ||(static_cast <bool> ((!ByCopy || isa<LambdaScopeInfo >(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by " "*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1356, __extension__ __PRETTY_FUNCTION__ )) | |||
1354 | isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&(static_cast <bool> ((!ByCopy || isa<LambdaScopeInfo >(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by " "*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1356, __extension__ __PRETTY_FUNCTION__ )) | |||
1355 | "Only a lambda can capture the enclosing object (referred to by "(static_cast <bool> ((!ByCopy || isa<LambdaScopeInfo >(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by " "*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1356, __extension__ __PRETTY_FUNCTION__ )) | |||
1356 | "*this) by copy")(static_cast <bool> ((!ByCopy || isa<LambdaScopeInfo >(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by " "*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1356, __extension__ __PRETTY_FUNCTION__ )); | |||
1357 | QualType ThisTy = getCurrentThisType(); | |||
1358 | for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; | |||
1359 | --idx, --NumCapturingClosures) { | |||
1360 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); | |||
1361 | ||||
1362 | // The type of the corresponding data member (not a 'this' pointer if 'by | |||
1363 | // copy'). | |||
1364 | QualType CaptureType = ThisTy; | |||
1365 | if (ByCopy) { | |||
1366 | // If we are capturing the object referred to by '*this' by copy, ignore | |||
1367 | // any cv qualifiers inherited from the type of the member function for | |||
1368 | // the type of the closure-type's corresponding data member and any use | |||
1369 | // of 'this'. | |||
1370 | CaptureType = ThisTy->getPointeeType(); | |||
1371 | CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask); | |||
1372 | } | |||
1373 | ||||
1374 | bool isNested = NumCapturingClosures > 1; | |||
1375 | CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); | |||
1376 | } | |||
1377 | return false; | |||
1378 | } | |||
1379 | ||||
1380 | ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { | |||
1381 | /// C++ 9.3.2: In the body of a non-static member function, the keyword this | |||
1382 | /// is a non-lvalue expression whose value is the address of the object for | |||
1383 | /// which the function is called. | |||
1384 | ||||
1385 | QualType ThisTy = getCurrentThisType(); | |||
1386 | if (ThisTy.isNull()) | |||
1387 | return Diag(Loc, diag::err_invalid_this_use); | |||
1388 | return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false); | |||
1389 | } | |||
1390 | ||||
1391 | Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, | |||
1392 | bool IsImplicit) { | |||
1393 | if (getLangOpts().HLSL && Type.getTypePtr()->isPointerType()) { | |||
1394 | auto *This = new (Context) | |||
1395 | CXXThisExpr(Loc, Type.getTypePtr()->getPointeeType(), IsImplicit); | |||
1396 | This->setValueKind(ExprValueKind::VK_LValue); | |||
1397 | MarkThisReferenced(This); | |||
1398 | return This; | |||
1399 | } | |||
1400 | auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit); | |||
1401 | MarkThisReferenced(This); | |||
1402 | return This; | |||
1403 | } | |||
1404 | ||||
1405 | void Sema::MarkThisReferenced(CXXThisExpr *This) { | |||
1406 | CheckCXXThisCapture(This->getExprLoc()); | |||
1407 | } | |||
1408 | ||||
1409 | bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { | |||
1410 | // If we're outside the body of a member function, then we'll have a specified | |||
1411 | // type for 'this'. | |||
1412 | if (CXXThisTypeOverride.isNull()) | |||
1413 | return false; | |||
1414 | ||||
1415 | // Determine whether we're looking into a class that's currently being | |||
1416 | // defined. | |||
1417 | CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); | |||
1418 | return Class && Class->isBeingDefined(); | |||
1419 | } | |||
1420 | ||||
1421 | /// Parse construction of a specified type. | |||
1422 | /// Can be interpreted either as function-style casting ("int(x)") | |||
1423 | /// or class type construction ("ClassType(x,y,z)") | |||
1424 | /// or creation of a value-initialized type ("int()"). | |||
1425 | ExprResult | |||
1426 | Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, | |||
1427 | SourceLocation LParenOrBraceLoc, | |||
1428 | MultiExprArg exprs, | |||
1429 | SourceLocation RParenOrBraceLoc, | |||
1430 | bool ListInitialization) { | |||
1431 | if (!TypeRep) | |||
1432 | return ExprError(); | |||
1433 | ||||
1434 | TypeSourceInfo *TInfo; | |||
1435 | QualType Ty = GetTypeFromParser(TypeRep, &TInfo); | |||
1436 | if (!TInfo) | |||
1437 | TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); | |||
1438 | ||||
1439 | auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs, | |||
1440 | RParenOrBraceLoc, ListInitialization); | |||
1441 | // Avoid creating a non-type-dependent expression that contains typos. | |||
1442 | // Non-type-dependent expressions are liable to be discarded without | |||
1443 | // checking for embedded typos. | |||
1444 | if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && | |||
1445 | !Result.get()->isTypeDependent()) | |||
1446 | Result = CorrectDelayedTyposInExpr(Result.get()); | |||
1447 | else if (Result.isInvalid()) | |||
1448 | Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(), | |||
1449 | RParenOrBraceLoc, exprs, Ty); | |||
1450 | return Result; | |||
1451 | } | |||
1452 | ||||
1453 | ExprResult | |||
1454 | Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, | |||
1455 | SourceLocation LParenOrBraceLoc, | |||
1456 | MultiExprArg Exprs, | |||
1457 | SourceLocation RParenOrBraceLoc, | |||
1458 | bool ListInitialization) { | |||
1459 | QualType Ty = TInfo->getType(); | |||
1460 | SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); | |||
1461 | ||||
1462 | assert((!ListInitialization || Exprs.size() == 1) &&(static_cast <bool> ((!ListInitialization || Exprs.size () == 1) && "List initialization must have exactly one expression." ) ? void (0) : __assert_fail ("(!ListInitialization || Exprs.size() == 1) && \"List initialization must have exactly one expression.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1463, __extension__ __PRETTY_FUNCTION__ )) | |||
1463 | "List initialization must have exactly one expression.")(static_cast <bool> ((!ListInitialization || Exprs.size () == 1) && "List initialization must have exactly one expression." ) ? void (0) : __assert_fail ("(!ListInitialization || Exprs.size() == 1) && \"List initialization must have exactly one expression.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1463, __extension__ __PRETTY_FUNCTION__ )); | |||
1464 | SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); | |||
1465 | ||||
1466 | InitializedEntity Entity = | |||
1467 | InitializedEntity::InitializeTemporary(Context, TInfo); | |||
1468 | InitializationKind Kind = | |||
1469 | Exprs.size() | |||
1470 | ? ListInitialization | |||
1471 | ? InitializationKind::CreateDirectList( | |||
1472 | TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc) | |||
1473 | : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc, | |||
1474 | RParenOrBraceLoc) | |||
1475 | : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc, | |||
1476 | RParenOrBraceLoc); | |||
1477 | ||||
1478 | // C++1z [expr.type.conv]p1: | |||
1479 | // If the type is a placeholder for a deduced class type, [...perform class | |||
1480 | // template argument deduction...] | |||
1481 | // C++2b: | |||
1482 | // Otherwise, if the type contains a placeholder type, it is replaced by the | |||
1483 | // type determined by placeholder type deduction. | |||
1484 | if (const DeducedType *Deduced = Ty->getContainedDeducedType(); | |||
1485 | Deduced && !Deduced->isDeduced()) { | |||
1486 | if (isa<DeducedTemplateSpecializationType>(Deduced)) { | |||
1487 | Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, Kind, | |||
1488 | Exprs); | |||
1489 | if (Ty.isNull()) | |||
1490 | return ExprError(); | |||
1491 | Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); | |||
1492 | } else { | |||
1493 | assert(isa<AutoType>(Deduced))(static_cast <bool> (isa<AutoType>(Deduced)) ? void (0) : __assert_fail ("isa<AutoType>(Deduced)", "clang/lib/Sema/SemaExprCXX.cpp" , 1493, __extension__ __PRETTY_FUNCTION__)); | |||
1494 | MultiExprArg Inits = Exprs; | |||
1495 | if (ListInitialization) { | |||
1496 | auto *ILE = cast<InitListExpr>(Exprs[0]); | |||
1497 | Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits()); | |||
1498 | } | |||
1499 | ||||
1500 | if (Inits.empty()) | |||
1501 | return ExprError( | |||
1502 | Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression) | |||
1503 | << Ty << FullRange); | |||
1504 | if (Inits.size() > 1) { | |||
1505 | Expr *FirstBad = Inits[1]; | |||
1506 | return ExprError(Diag(FirstBad->getBeginLoc(), | |||
1507 | diag::err_auto_expr_init_multiple_expressions) | |||
1508 | << Ty << FullRange); | |||
1509 | } | |||
1510 | if (getLangOpts().CPlusPlus2b) { | |||
1511 | if (Ty->getAs<AutoType>()) | |||
1512 | Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange; | |||
1513 | } | |||
1514 | Expr *Deduce = Inits[0]; | |||
1515 | if (isa<InitListExpr>(Deduce)) | |||
1516 | return ExprError( | |||
1517 | Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces) | |||
1518 | << ListInitialization << Ty << FullRange); | |||
1519 | QualType DeducedType; | |||
1520 | TemplateDeductionInfo Info(Deduce->getExprLoc()); | |||
1521 | TemplateDeductionResult Result = | |||
1522 | DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info); | |||
1523 | if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) | |||
1524 | return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure) | |||
1525 | << Ty << Deduce->getType() << FullRange | |||
1526 | << Deduce->getSourceRange()); | |||
1527 | if (DeducedType.isNull()) { | |||
1528 | assert(Result == TDK_AlreadyDiagnosed)(static_cast <bool> (Result == TDK_AlreadyDiagnosed) ? void (0) : __assert_fail ("Result == TDK_AlreadyDiagnosed", "clang/lib/Sema/SemaExprCXX.cpp" , 1528, __extension__ __PRETTY_FUNCTION__)); | |||
1529 | return ExprError(); | |||
1530 | } | |||
1531 | ||||
1532 | Ty = DeducedType; | |||
1533 | Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); | |||
1534 | } | |||
1535 | } | |||
1536 | ||||
1537 | if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) { | |||
1538 | // FIXME: CXXUnresolvedConstructExpr does not model list-initialization | |||
1539 | // directly. We work around this by dropping the locations of the braces. | |||
1540 | SourceRange Locs = ListInitialization | |||
1541 | ? SourceRange() | |||
1542 | : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); | |||
1543 | return CXXUnresolvedConstructExpr::Create(Context, Ty.getNonReferenceType(), | |||
1544 | TInfo, Locs.getBegin(), Exprs, | |||
1545 | Locs.getEnd()); | |||
1546 | } | |||
1547 | ||||
1548 | // C++ [expr.type.conv]p1: | |||
1549 | // If the expression list is a parenthesized single expression, the type | |||
1550 | // conversion expression is equivalent (in definedness, and if defined in | |||
1551 | // meaning) to the corresponding cast expression. | |||
1552 | if (Exprs.size() == 1 && !ListInitialization && | |||
1553 | !isa<InitListExpr>(Exprs[0])) { | |||
1554 | Expr *Arg = Exprs[0]; | |||
1555 | return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg, | |||
1556 | RParenOrBraceLoc); | |||
1557 | } | |||
1558 | ||||
1559 | // For an expression of the form T(), T shall not be an array type. | |||
1560 | QualType ElemTy = Ty; | |||
1561 | if (Ty->isArrayType()) { | |||
1562 | if (!ListInitialization) | |||
1563 | return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) | |||
1564 | << FullRange); | |||
1565 | ElemTy = Context.getBaseElementType(Ty); | |||
1566 | } | |||
1567 | ||||
1568 | // Only construct objects with object types. | |||
1569 | // The standard doesn't explicitly forbid function types here, but that's an | |||
1570 | // obvious oversight, as there's no way to dynamically construct a function | |||
1571 | // in general. | |||
1572 | if (Ty->isFunctionType()) | |||
1573 | return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) | |||
1574 | << Ty << FullRange); | |||
1575 | ||||
1576 | // C++17 [expr.type.conv]p2: | |||
1577 | // If the type is cv void and the initializer is (), the expression is a | |||
1578 | // prvalue of the specified type that performs no initialization. | |||
1579 | if (!Ty->isVoidType() && | |||
1580 | RequireCompleteType(TyBeginLoc, ElemTy, | |||
1581 | diag::err_invalid_incomplete_type_use, FullRange)) | |||
1582 | return ExprError(); | |||
1583 | ||||
1584 | // Otherwise, the expression is a prvalue of the specified type whose | |||
1585 | // result object is direct-initialized (11.6) with the initializer. | |||
1586 | InitializationSequence InitSeq(*this, Entity, Kind, Exprs); | |||
1587 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); | |||
1588 | ||||
1589 | if (Result.isInvalid()) | |||
1590 | return Result; | |||
1591 | ||||
1592 | Expr *Inner = Result.get(); | |||
1593 | if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) | |||
1594 | Inner = BTE->getSubExpr(); | |||
1595 | if (!isa<CXXTemporaryObjectExpr>(Inner) && | |||
1596 | !isa<CXXScalarValueInitExpr>(Inner)) { | |||
1597 | // If we created a CXXTemporaryObjectExpr, that node also represents the | |||
1598 | // functional cast. Otherwise, create an explicit cast to represent | |||
1599 | // the syntactic form of a functional-style cast that was used here. | |||
1600 | // | |||
1601 | // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr | |||
1602 | // would give a more consistent AST representation than using a | |||
1603 | // CXXTemporaryObjectExpr. It's also weird that the functional cast | |||
1604 | // is sometimes handled by initialization and sometimes not. | |||
1605 | QualType ResultType = Result.get()->getType(); | |||
1606 | SourceRange Locs = ListInitialization | |||
1607 | ? SourceRange() | |||
1608 | : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); | |||
1609 | Result = CXXFunctionalCastExpr::Create( | |||
1610 | Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp, | |||
1611 | Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(), | |||
1612 | Locs.getBegin(), Locs.getEnd()); | |||
1613 | } | |||
1614 | ||||
1615 | return Result; | |||
1616 | } | |||
1617 | ||||
1618 | bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { | |||
1619 | // [CUDA] Ignore this function, if we can't call it. | |||
1620 | const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); | |||
1621 | if (getLangOpts().CUDA) { | |||
1622 | auto CallPreference = IdentifyCUDAPreference(Caller, Method); | |||
1623 | // If it's not callable at all, it's not the right function. | |||
1624 | if (CallPreference < CFP_WrongSide) | |||
1625 | return false; | |||
1626 | if (CallPreference == CFP_WrongSide) { | |||
1627 | // Maybe. We have to check if there are better alternatives. | |||
1628 | DeclContext::lookup_result R = | |||
1629 | Method->getDeclContext()->lookup(Method->getDeclName()); | |||
1630 | for (const auto *D : R) { | |||
1631 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) { | |||
1632 | if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide) | |||
1633 | return false; | |||
1634 | } | |||
1635 | } | |||
1636 | // We've found no better variants. | |||
1637 | } | |||
1638 | } | |||
1639 | ||||
1640 | SmallVector<const FunctionDecl*, 4> PreventedBy; | |||
1641 | bool Result = Method->isUsualDeallocationFunction(PreventedBy); | |||
1642 | ||||
1643 | if (Result || !getLangOpts().CUDA || PreventedBy.empty()) | |||
1644 | return Result; | |||
1645 | ||||
1646 | // In case of CUDA, return true if none of the 1-argument deallocator | |||
1647 | // functions are actually callable. | |||
1648 | return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) { | |||
1649 | assert(FD->getNumParams() == 1 &&(static_cast <bool> (FD->getNumParams() == 1 && "Only single-operand functions should be in PreventedBy") ? void (0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1650, __extension__ __PRETTY_FUNCTION__ )) | |||
1650 | "Only single-operand functions should be in PreventedBy")(static_cast <bool> (FD->getNumParams() == 1 && "Only single-operand functions should be in PreventedBy") ? void (0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1650, __extension__ __PRETTY_FUNCTION__ )); | |||
1651 | return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice; | |||
1652 | }); | |||
1653 | } | |||
1654 | ||||
1655 | /// Determine whether the given function is a non-placement | |||
1656 | /// deallocation function. | |||
1657 | static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { | |||
1658 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) | |||
1659 | return S.isUsualDeallocationFunction(Method); | |||
1660 | ||||
1661 | if (FD->getOverloadedOperator() != OO_Delete && | |||
1662 | FD->getOverloadedOperator() != OO_Array_Delete) | |||
1663 | return false; | |||
1664 | ||||
1665 | unsigned UsualParams = 1; | |||
1666 | ||||
1667 | if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && | |||
1668 | S.Context.hasSameUnqualifiedType( | |||
1669 | FD->getParamDecl(UsualParams)->getType(), | |||
1670 | S.Context.getSizeType())) | |||
1671 | ++UsualParams; | |||
1672 | ||||
1673 | if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && | |||
1674 | S.Context.hasSameUnqualifiedType( | |||
1675 | FD->getParamDecl(UsualParams)->getType(), | |||
1676 | S.Context.getTypeDeclType(S.getStdAlignValT()))) | |||
1677 | ++UsualParams; | |||
1678 | ||||
1679 | return UsualParams == FD->getNumParams(); | |||
1680 | } | |||
1681 | ||||
1682 | namespace { | |||
1683 | struct UsualDeallocFnInfo { | |||
1684 | UsualDeallocFnInfo() : Found(), FD(nullptr) {} | |||
1685 | UsualDeallocFnInfo(Sema &S, DeclAccessPair Found) | |||
1686 | : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())), | |||
1687 | Destroying(false), HasSizeT(false), HasAlignValT(false), | |||
1688 | CUDAPref(Sema::CFP_Native) { | |||
1689 | // A function template declaration is never a usual deallocation function. | |||
1690 | if (!FD) | |||
1691 | return; | |||
1692 | unsigned NumBaseParams = 1; | |||
1693 | if (FD->isDestroyingOperatorDelete()) { | |||
1694 | Destroying = true; | |||
1695 | ++NumBaseParams; | |||
1696 | } | |||
1697 | ||||
1698 | if (NumBaseParams < FD->getNumParams() && | |||
1699 | S.Context.hasSameUnqualifiedType( | |||
1700 | FD->getParamDecl(NumBaseParams)->getType(), | |||
1701 | S.Context.getSizeType())) { | |||
1702 | ++NumBaseParams; | |||
1703 | HasSizeT = true; | |||
1704 | } | |||
1705 | ||||
1706 | if (NumBaseParams < FD->getNumParams() && | |||
1707 | FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) { | |||
1708 | ++NumBaseParams; | |||
1709 | HasAlignValT = true; | |||
1710 | } | |||
1711 | ||||
1712 | // In CUDA, determine how much we'd like / dislike to call this. | |||
1713 | if (S.getLangOpts().CUDA) | |||
1714 | if (auto *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) | |||
1715 | CUDAPref = S.IdentifyCUDAPreference(Caller, FD); | |||
1716 | } | |||
1717 | ||||
1718 | explicit operator bool() const { return FD; } | |||
1719 | ||||
1720 | bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize, | |||
1721 | bool WantAlign) const { | |||
1722 | // C++ P0722: | |||
1723 | // A destroying operator delete is preferred over a non-destroying | |||
1724 | // operator delete. | |||
1725 | if (Destroying != Other.Destroying) | |||
1726 | return Destroying; | |||
1727 | ||||
1728 | // C++17 [expr.delete]p10: | |||
1729 | // If the type has new-extended alignment, a function with a parameter | |||
1730 | // of type std::align_val_t is preferred; otherwise a function without | |||
1731 | // such a parameter is preferred | |||
1732 | if (HasAlignValT != Other.HasAlignValT) | |||
1733 | return HasAlignValT == WantAlign; | |||
1734 | ||||
1735 | if (HasSizeT != Other.HasSizeT) | |||
1736 | return HasSizeT == WantSize; | |||
1737 | ||||
1738 | // Use CUDA call preference as a tiebreaker. | |||
1739 | return CUDAPref > Other.CUDAPref; | |||
1740 | } | |||
1741 | ||||
1742 | DeclAccessPair Found; | |||
1743 | FunctionDecl *FD; | |||
1744 | bool Destroying, HasSizeT, HasAlignValT; | |||
1745 | Sema::CUDAFunctionPreference CUDAPref; | |||
1746 | }; | |||
1747 | } | |||
1748 | ||||
1749 | /// Determine whether a type has new-extended alignment. This may be called when | |||
1750 | /// the type is incomplete (for a delete-expression with an incomplete pointee | |||
1751 | /// type), in which case it will conservatively return false if the alignment is | |||
1752 | /// not known. | |||
1753 | static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { | |||
1754 | return S.getLangOpts().AlignedAllocation && | |||
1755 | S.getASTContext().getTypeAlignIfKnown(AllocType) > | |||
1756 | S.getASTContext().getTargetInfo().getNewAlign(); | |||
1757 | } | |||
1758 | ||||
1759 | /// Select the correct "usual" deallocation function to use from a selection of | |||
1760 | /// deallocation functions (either global or class-scope). | |||
1761 | static UsualDeallocFnInfo resolveDeallocationOverload( | |||
1762 | Sema &S, LookupResult &R, bool WantSize, bool WantAlign, | |||
1763 | llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { | |||
1764 | UsualDeallocFnInfo Best; | |||
1765 | ||||
1766 | for (auto I = R.begin(), E = R.end(); I != E; ++I) { | |||
1767 | UsualDeallocFnInfo Info(S, I.getPair()); | |||
1768 | if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) || | |||
1769 | Info.CUDAPref == Sema::CFP_Never) | |||
1770 | continue; | |||
1771 | ||||
1772 | if (!Best) { | |||
1773 | Best = Info; | |||
1774 | if (BestFns) | |||
1775 | BestFns->push_back(Info); | |||
1776 | continue; | |||
1777 | } | |||
1778 | ||||
1779 | if (Best.isBetterThan(Info, WantSize, WantAlign)) | |||
1780 | continue; | |||
1781 | ||||
1782 | // If more than one preferred function is found, all non-preferred | |||
1783 | // functions are eliminated from further consideration. | |||
1784 | if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign)) | |||
1785 | BestFns->clear(); | |||
1786 | ||||
1787 | Best = Info; | |||
1788 | if (BestFns) | |||
1789 | BestFns->push_back(Info); | |||
1790 | } | |||
1791 | ||||
1792 | return Best; | |||
1793 | } | |||
1794 | ||||
1795 | /// Determine whether a given type is a class for which 'delete[]' would call | |||
1796 | /// a member 'operator delete[]' with a 'size_t' parameter. This implies that | |||
1797 | /// we need to store the array size (even if the type is | |||
1798 | /// trivially-destructible). | |||
1799 | static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, | |||
1800 | QualType allocType) { | |||
1801 | const RecordType *record = | |||
1802 | allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); | |||
1803 | if (!record) return false; | |||
1804 | ||||
1805 | // Try to find an operator delete[] in class scope. | |||
1806 | ||||
1807 | DeclarationName deleteName = | |||
1808 | S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); | |||
1809 | LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); | |||
1810 | S.LookupQualifiedName(ops, record->getDecl()); | |||
1811 | ||||
1812 | // We're just doing this for information. | |||
1813 | ops.suppressDiagnostics(); | |||
1814 | ||||
1815 | // Very likely: there's no operator delete[]. | |||
1816 | if (ops.empty()) return false; | |||
1817 | ||||
1818 | // If it's ambiguous, it should be illegal to call operator delete[] | |||
1819 | // on this thing, so it doesn't matter if we allocate extra space or not. | |||
1820 | if (ops.isAmbiguous()) return false; | |||
1821 | ||||
1822 | // C++17 [expr.delete]p10: | |||
1823 | // If the deallocation functions have class scope, the one without a | |||
1824 | // parameter of type std::size_t is selected. | |||
1825 | auto Best = resolveDeallocationOverload( | |||
1826 | S, ops, /*WantSize*/false, | |||
1827 | /*WantAlign*/hasNewExtendedAlignment(S, allocType)); | |||
1828 | return Best && Best.HasSizeT; | |||
1829 | } | |||
1830 | ||||
1831 | /// Parsed a C++ 'new' expression (C++ 5.3.4). | |||
1832 | /// | |||
1833 | /// E.g.: | |||
1834 | /// @code new (memory) int[size][4] @endcode | |||
1835 | /// or | |||
1836 | /// @code ::new Foo(23, "hello") @endcode | |||
1837 | /// | |||
1838 | /// \param StartLoc The first location of the expression. | |||
1839 | /// \param UseGlobal True if 'new' was prefixed with '::'. | |||
1840 | /// \param PlacementLParen Opening paren of the placement arguments. | |||
1841 | /// \param PlacementArgs Placement new arguments. | |||
1842 | /// \param PlacementRParen Closing paren of the placement arguments. | |||
1843 | /// \param TypeIdParens If the type is in parens, the source range. | |||
1844 | /// \param D The type to be allocated, as well as array dimensions. | |||
1845 | /// \param Initializer The initializing expression or initializer-list, or null | |||
1846 | /// if there is none. | |||
1847 | ExprResult | |||
1848 | Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, | |||
1849 | SourceLocation PlacementLParen, MultiExprArg PlacementArgs, | |||
1850 | SourceLocation PlacementRParen, SourceRange TypeIdParens, | |||
1851 | Declarator &D, Expr *Initializer) { | |||
1852 | Optional<Expr *> ArraySize; | |||
1853 | // If the specified type is an array, unwrap it and save the expression. | |||
1854 | if (D.getNumTypeObjects() > 0 && | |||
1855 | D.getTypeObject(0).Kind == DeclaratorChunk::Array) { | |||
1856 | DeclaratorChunk &Chunk = D.getTypeObject(0); | |||
1857 | if (D.getDeclSpec().hasAutoTypeSpec()) | |||
1858 | return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) | |||
1859 | << D.getSourceRange()); | |||
1860 | if (Chunk.Arr.hasStatic) | |||
1861 | return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) | |||
1862 | << D.getSourceRange()); | |||
1863 | if (!Chunk.Arr.NumElts && !Initializer) | |||
1864 | return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) | |||
1865 | << D.getSourceRange()); | |||
1866 | ||||
1867 | ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); | |||
1868 | D.DropFirstTypeObject(); | |||
1869 | } | |||
1870 | ||||
1871 | // Every dimension shall be of constant size. | |||
1872 | if (ArraySize) { | |||
1873 | for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { | |||
1874 | if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) | |||
1875 | break; | |||
1876 | ||||
1877 | DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; | |||
1878 | if (Expr *NumElts = (Expr *)Array.NumElts) { | |||
1879 | if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { | |||
1880 | // FIXME: GCC permits constant folding here. We should either do so consistently | |||
1881 | // or not do so at all, rather than changing behavior in C++14 onwards. | |||
1882 | if (getLangOpts().CPlusPlus14) { | |||
1883 | // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator | |||
1884 | // shall be a converted constant expression (5.19) of type std::size_t | |||
1885 | // and shall evaluate to a strictly positive value. | |||
1886 | llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); | |||
1887 | Array.NumElts | |||
1888 | = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value, | |||
1889 | CCEK_ArrayBound) | |||
1890 | .get(); | |||
1891 | } else { | |||
1892 | Array.NumElts = | |||
1893 | VerifyIntegerConstantExpression( | |||
1894 | NumElts, nullptr, diag::err_new_array_nonconst, AllowFold) | |||
1895 | .get(); | |||
1896 | } | |||
1897 | if (!Array.NumElts) | |||
1898 | return ExprError(); | |||
1899 | } | |||
1900 | } | |||
1901 | } | |||
1902 | } | |||
1903 | ||||
1904 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr); | |||
1905 | QualType AllocType = TInfo->getType(); | |||
1906 | if (D.isInvalidType()) | |||
1907 | return ExprError(); | |||
1908 | ||||
1909 | SourceRange DirectInitRange; | |||
1910 | if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) | |||
1911 | DirectInitRange = List->getSourceRange(); | |||
1912 | ||||
1913 | return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal, | |||
1914 | PlacementLParen, PlacementArgs, PlacementRParen, | |||
1915 | TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange, | |||
1916 | Initializer); | |||
1917 | } | |||
1918 | ||||
1919 | static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, | |||
1920 | Expr *Init) { | |||
1921 | if (!Init) | |||
1922 | return true; | |||
1923 | if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) | |||
1924 | return PLE->getNumExprs() == 0; | |||
1925 | if (isa<ImplicitValueInitExpr>(Init)) | |||
1926 | return true; | |||
1927 | else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) | |||
1928 | return !CCE->isListInitialization() && | |||
1929 | CCE->getConstructor()->isDefaultConstructor(); | |||
1930 | else if (Style == CXXNewExpr::ListInit) { | |||
1931 | assert(isa<InitListExpr>(Init) &&(static_cast <bool> (isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays.") ? void (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1932, __extension__ __PRETTY_FUNCTION__ )) | |||
1932 | "Shouldn't create list CXXConstructExprs for arrays.")(static_cast <bool> (isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays.") ? void (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1932, __extension__ __PRETTY_FUNCTION__ )); | |||
1933 | return true; | |||
1934 | } | |||
1935 | return false; | |||
1936 | } | |||
1937 | ||||
1938 | bool | |||
1939 | Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { | |||
1940 | if (!getLangOpts().AlignedAllocationUnavailable) | |||
1941 | return false; | |||
1942 | if (FD.isDefined()) | |||
1943 | return false; | |||
1944 | Optional<unsigned> AlignmentParam; | |||
1945 | if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) && | |||
1946 | AlignmentParam) | |||
1947 | return true; | |||
1948 | return false; | |||
1949 | } | |||
1950 | ||||
1951 | // Emit a diagnostic if an aligned allocation/deallocation function that is not | |||
1952 | // implemented in the standard library is selected. | |||
1953 | void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, | |||
1954 | SourceLocation Loc) { | |||
1955 | if (isUnavailableAlignedAllocationFunction(FD)) { | |||
1956 | const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); | |||
1957 | StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( | |||
1958 | getASTContext().getTargetInfo().getPlatformName()); | |||
1959 | VersionTuple OSVersion = alignedAllocMinVersion(T.getOS()); | |||
1960 | ||||
1961 | OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator(); | |||
1962 | bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete; | |||
1963 | Diag(Loc, diag::err_aligned_allocation_unavailable) | |||
1964 | << IsDelete << FD.getType().getAsString() << OSName | |||
1965 | << OSVersion.getAsString() << OSVersion.empty(); | |||
1966 | Diag(Loc, diag::note_silence_aligned_allocation_unavailable); | |||
1967 | } | |||
1968 | } | |||
1969 | ||||
1970 | ExprResult | |||
1971 | Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, | |||
1972 | SourceLocation PlacementLParen, | |||
1973 | MultiExprArg PlacementArgs, | |||
1974 | SourceLocation PlacementRParen, | |||
1975 | SourceRange TypeIdParens, | |||
1976 | QualType AllocType, | |||
1977 | TypeSourceInfo *AllocTypeInfo, | |||
1978 | Optional<Expr *> ArraySize, | |||
1979 | SourceRange DirectInitRange, | |||
1980 | Expr *Initializer) { | |||
1981 | SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); | |||
1982 | SourceLocation StartLoc = Range.getBegin(); | |||
1983 | ||||
1984 | CXXNewExpr::InitializationStyle initStyle; | |||
1985 | if (DirectInitRange.isValid()) { | |||
1986 | assert(Initializer && "Have parens but no initializer.")(static_cast <bool> (Initializer && "Have parens but no initializer." ) ? void (0) : __assert_fail ("Initializer && \"Have parens but no initializer.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1986, __extension__ __PRETTY_FUNCTION__ )); | |||
1987 | initStyle = CXXNewExpr::CallInit; | |||
1988 | } else if (Initializer && isa<InitListExpr>(Initializer)) | |||
| ||||
1989 | initStyle = CXXNewExpr::ListInit; | |||
1990 | else { | |||
1991 | assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr >(Initializer) || isa<CXXConstructExpr>(Initializer) ) && "Initializer expression that cannot have been implicitly created." ) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1993, __extension__ __PRETTY_FUNCTION__ )) | |||
1992 | isa<CXXConstructExpr>(Initializer)) &&(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr >(Initializer) || isa<CXXConstructExpr>(Initializer) ) && "Initializer expression that cannot have been implicitly created." ) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1993, __extension__ __PRETTY_FUNCTION__ )) | |||
1993 | "Initializer expression that cannot have been implicitly created.")(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr >(Initializer) || isa<CXXConstructExpr>(Initializer) ) && "Initializer expression that cannot have been implicitly created." ) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1993, __extension__ __PRETTY_FUNCTION__ )); | |||
1994 | initStyle = CXXNewExpr::NoInit; | |||
1995 | } | |||
1996 | ||||
1997 | MultiExprArg Exprs(&Initializer, Initializer
| |||
1998 | if (ParenListExpr *List
| |||
1999 | assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init")(static_cast <bool> (initStyle == CXXNewExpr::CallInit && "paren init for non-call init") ? void (0) : __assert_fail ( "initStyle == CXXNewExpr::CallInit && \"paren init for non-call init\"" , "clang/lib/Sema/SemaExprCXX.cpp", 1999, __extension__ __PRETTY_FUNCTION__ )); | |||
2000 | Exprs = MultiExprArg(List->getExprs(), List->getNumExprs()); | |||
2001 | } | |||
2002 | ||||
2003 | // C++11 [expr.new]p15: | |||
2004 | // A new-expression that creates an object of type T initializes that | |||
2005 | // object as follows: | |||
2006 | InitializationKind Kind | |||
2007 | // - If the new-initializer is omitted, the object is default- | |||
2008 | // initialized (8.5); if no initialization is performed, | |||
2009 | // the object has indeterminate value | |||
2010 | = initStyle
| |||
2011 | ? InitializationKind::CreateDefault(TypeRange.getBegin()) | |||
2012 | // - Otherwise, the new-initializer is interpreted according to | |||
2013 | // the | |||
2014 | // initialization rules of 8.5 for direct-initialization. | |||
2015 | : initStyle
| |||
2016 | ? InitializationKind::CreateDirectList( | |||
2017 | TypeRange.getBegin(), Initializer->getBeginLoc(), | |||
| ||||
2018 | Initializer->getEndLoc()) | |||
2019 | : InitializationKind::CreateDirect(TypeRange.getBegin(), | |||
2020 | DirectInitRange.getBegin(), | |||
2021 | DirectInitRange.getEnd()); | |||
2022 | ||||
2023 | // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. | |||
2024 | if (const DeducedType *Deduced = AllocType->getContainedDeducedType(); | |||
2025 | Deduced && !Deduced->isDeduced()) { | |||
2026 | if (isa<DeducedTemplateSpecializationType>(Deduced)) { | |||
2027 | if (ArraySize) | |||
2028 | return ExprError( | |||
2029 | Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), | |||
2030 | diag::err_deduced_class_template_compound_type) | |||
2031 | << /*array*/ 2 | |||
2032 | << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); | |||
2033 | ||||
2034 | InitializedEntity Entity = | |||
2035 | InitializedEntity::InitializeNew(StartLoc, AllocType); | |||
2036 | AllocType = DeduceTemplateSpecializationFromInitializer( | |||
2037 | AllocTypeInfo, Entity, Kind, Exprs); | |||
2038 | if (AllocType.isNull()) | |||
2039 | return ExprError(); | |||
2040 | } else { | |||
2041 | assert(isa<AutoType>(Deduced))(static_cast <bool> (isa<AutoType>(Deduced)) ? void (0) : __assert_fail ("isa<AutoType>(Deduced)", "clang/lib/Sema/SemaExprCXX.cpp" , 2041, __extension__ __PRETTY_FUNCTION__)); | |||
2042 | MultiExprArg Inits = Exprs; | |||
2043 | bool Braced = (initStyle == CXXNewExpr::ListInit); | |||
2044 | if (Braced) { | |||
2045 | auto *ILE = cast<InitListExpr>(Exprs[0]); | |||
2046 | Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits()); | |||
2047 | } | |||
2048 | ||||
2049 | if (initStyle == CXXNewExpr::NoInit || Inits.empty()) | |||
2050 | return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) | |||
2051 | << AllocType << TypeRange); | |||
2052 | if (Inits.size() > 1) { | |||
2053 | Expr *FirstBad = Inits[1]; | |||
2054 | return ExprError(Diag(FirstBad->getBeginLoc(), | |||
2055 | diag::err_auto_new_ctor_multiple_expressions) | |||
2056 | << AllocType << TypeRange); | |||
2057 | } | |||
2058 | if (Braced && !getLangOpts().CPlusPlus17) | |||
2059 | Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) | |||
2060 | << AllocType << TypeRange; | |||
2061 | Expr *Deduce = Inits[0]; | |||
2062 | if (isa<InitListExpr>(Deduce)) | |||
2063 | return ExprError( | |||
2064 | Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces) | |||
2065 | << Braced << AllocType << TypeRange); | |||
2066 | QualType DeducedType; | |||
2067 | TemplateDeductionInfo Info(Deduce->getExprLoc()); | |||
2068 | TemplateDeductionResult Result = DeduceAutoType( | |||
2069 | AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info); | |||
2070 | if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) | |||
2071 | return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) | |||
2072 | << AllocType << Deduce->getType() << TypeRange | |||
2073 | << Deduce->getSourceRange()); | |||
2074 | if (DeducedType.isNull()) { | |||
2075 | assert(Result == TDK_AlreadyDiagnosed)(static_cast <bool> (Result == TDK_AlreadyDiagnosed) ? void (0) : __assert_fail ("Result == TDK_AlreadyDiagnosed", "clang/lib/Sema/SemaExprCXX.cpp" , 2075, __extension__ __PRETTY_FUNCTION__)); | |||
2076 | return ExprError(); | |||
2077 | } | |||
2078 | AllocType = DeducedType; | |||
2079 | } | |||
2080 | } | |||
2081 | ||||
2082 | // Per C++0x [expr.new]p5, the type being constructed may be a | |||
2083 | // typedef of an array type. | |||
2084 | if (!ArraySize) { | |||
2085 | if (const ConstantArrayType *Array | |||
2086 | = Context.getAsConstantArrayType(AllocType)) { | |||
2087 | ArraySize = IntegerLiteral::Create(Context, Array->getSize(), | |||
2088 | Context.getSizeType(), | |||
2089 | TypeRange.getEnd()); | |||
2090 | AllocType = Array->getElementType(); | |||
2091 | } | |||
2092 | } | |||
2093 | ||||
2094 | if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) | |||
2095 | return ExprError(); | |||
2096 | ||||
2097 | if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin())) | |||
2098 | return ExprError(); | |||
2099 | ||||
2100 | // In ARC, infer 'retaining' for the allocated | |||
2101 | if (getLangOpts().ObjCAutoRefCount && | |||
2102 | AllocType.getObjCLifetime() == Qualifiers::OCL_None && | |||
2103 | AllocType->isObjCLifetimeType()) { | |||
2104 | AllocType = Context.getLifetimeQualifiedType(AllocType, | |||
2105 | AllocType->getObjCARCImplicitLifetime()); | |||
2106 | } | |||
2107 | ||||
2108 | QualType ResultType = Context.getPointerType(AllocType); | |||
2109 | ||||
2110 | if (ArraySize && *ArraySize && | |||
2111 | (*ArraySize)->getType()->isNonOverloadPlaceholderType()) { | |||
2112 | ExprResult result = CheckPlaceholderExpr(*ArraySize); | |||
2113 | if (result.isInvalid()) return ExprError(); | |||
2114 | ArraySize = result.get(); | |||
2115 | } | |||
2116 | // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have | |||
2117 | // integral or enumeration type with a non-negative value." | |||
2118 | // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped | |||
2119 | // enumeration type, or a class type for which a single non-explicit | |||
2120 | // conversion function to integral or unscoped enumeration type exists. | |||
2121 | // C++1y [expr.new]p6: The expression [...] is implicitly converted to | |||
2122 | // std::size_t. | |||
2123 | llvm::Optional<uint64_t> KnownArraySize; | |||
2124 | if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { | |||
2125 | ExprResult ConvertedSize; | |||
2126 | if (getLangOpts().CPlusPlus14) { | |||
2127 | assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?")(static_cast <bool> (Context.getTargetInfo().getIntWidth () && "Builtin type of size 0?") ? void (0) : __assert_fail ("Context.getTargetInfo().getIntWidth() && \"Builtin type of size 0?\"" , "clang/lib/Sema/SemaExprCXX.cpp", 2127, __extension__ __PRETTY_FUNCTION__ )); | |||
2128 | ||||
2129 | ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(), | |||
2130 | AA_Converting); | |||
2131 | ||||
2132 | if (!ConvertedSize.isInvalid() && | |||
2133 | (*ArraySize)->getType()->getAs<RecordType>()) | |||
2134 | // Diagnose the compatibility of this conversion. | |||
2135 | Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) | |||
2136 | << (*ArraySize)->getType() << 0 << "'size_t'"; | |||
2137 | } else { | |||
2138 | class SizeConvertDiagnoser : public ICEConvertDiagnoser { | |||
2139 | protected: | |||
2140 | Expr *ArraySize; | |||
2141 | ||||
2142 | public: | |||
2143 | SizeConvertDiagnoser(Expr *ArraySize) | |||
2144 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), | |||
2145 | ArraySize(ArraySize) {} | |||
2146 | ||||
2147 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, | |||
2148 | QualType T) override { | |||
2149 | return S.Diag(Loc, diag::err_array_size_not_integral) | |||
2150 | << S.getLangOpts().CPlusPlus11 << T; | |||
2151 | } | |||
2152 | ||||
2153 | SemaDiagnosticBuilder diagnoseIncomplete( | |||
2154 | Sema &S, SourceLocation Loc, QualType T) override { | |||
2155 | return S.Diag(Loc, diag::err_array_size_incomplete_type) | |||
2156 | << T << ArraySize->getSourceRange(); | |||
2157 | } | |||
2158 | ||||
2159 | SemaDiagnosticBuilder diagnoseExplicitConv( | |||
2160 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | |||
2161 | return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; | |||
2162 | } | |||
2163 | ||||
2164 | SemaDiagnosticBuilder noteExplicitConv( | |||
2165 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | |||
2166 | return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) | |||
2167 | << ConvTy->isEnumeralType() << ConvTy; | |||
2168 | } | |||
2169 | ||||
2170 | SemaDiagnosticBuilder diagnoseAmbiguous( | |||
2171 | Sema &S, SourceLocation Loc, QualType T) override { | |||
2172 | return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; | |||
2173 | } | |||
2174 | ||||
2175 | SemaDiagnosticBuilder noteAmbiguous( | |||
2176 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | |||
2177 | return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) | |||
2178 | << ConvTy->isEnumeralType() << ConvTy; | |||
2179 | } | |||
2180 | ||||
2181 | SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, | |||
2182 | QualType T, | |||
2183 | QualType ConvTy) override { | |||
2184 | return S.Diag(Loc, | |||
2185 | S.getLangOpts().CPlusPlus11 | |||
2186 | ? diag::warn_cxx98_compat_array_size_conversion | |||
2187 | : diag::ext_array_size_conversion) | |||
2188 | << T << ConvTy->isEnumeralType() << ConvTy; | |||
2189 | } | |||
2190 | } SizeDiagnoser(*ArraySize); | |||
2191 | ||||
2192 | ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize, | |||
2193 | SizeDiagnoser); | |||
2194 | } | |||
2195 | if (ConvertedSize.isInvalid()) | |||
2196 | return ExprError(); | |||
2197 | ||||
2198 | ArraySize = ConvertedSize.get(); | |||
2199 | QualType SizeType = (*ArraySize)->getType(); | |||
2200 | ||||
2201 | if (!SizeType->isIntegralOrUnscopedEnumerationType()) | |||
2202 | return ExprError(); | |||
2203 | ||||
2204 | // C++98 [expr.new]p7: | |||
2205 | // The expression in a direct-new-declarator shall have integral type | |||
2206 | // with a non-negative value. | |||
2207 | // | |||
2208 | // Let's see if this is a constant < 0. If so, we reject it out of hand, | |||
2209 | // per CWG1464. Otherwise, if it's not a constant, we must have an | |||
2210 | // unparenthesized array type. | |||
2211 | ||||
2212 | // We've already performed any required implicit conversion to integer or | |||
2213 | // unscoped enumeration type. | |||
2214 | // FIXME: Per CWG1464, we are required to check the value prior to | |||
2215 | // converting to size_t. This will never find a negative array size in | |||
2216 | // C++14 onwards, because Value is always unsigned here! | |||
2217 | if (Optional<llvm::APSInt> Value = | |||
2218 | (*ArraySize)->getIntegerConstantExpr(Context)) { | |||
2219 | if (Value->isSigned() && Value->isNegative()) { | |||
2220 | return ExprError(Diag((*ArraySize)->getBeginLoc(), | |||
2221 | diag::err_typecheck_negative_array_size) | |||
2222 | << (*ArraySize)->getSourceRange()); | |||
2223 | } | |||
2224 | ||||
2225 | if (!AllocType->isDependentType()) { | |||
2226 | unsigned ActiveSizeBits = | |||
2227 | ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value); | |||
2228 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) | |||
2229 | return ExprError( | |||
2230 | Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) | |||
2231 | << toString(*Value, 10) << (*ArraySize)->getSourceRange()); | |||
2232 | } | |||
2233 | ||||
2234 | KnownArraySize = Value->getZExtValue(); | |||
2235 | } else if (TypeIdParens.isValid()) { | |||
2236 | // Can't have dynamic array size when the type-id is in parentheses. | |||
2237 | Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) | |||
2238 | << (*ArraySize)->getSourceRange() | |||
2239 | << FixItHint::CreateRemoval(TypeIdParens.getBegin()) | |||
2240 | << FixItHint::CreateRemoval(TypeIdParens.getEnd()); | |||
2241 | ||||
2242 | TypeIdParens = SourceRange(); | |||
2243 | } | |||
2244 | ||||
2245 | // Note that we do *not* convert the argument in any way. It can | |||
2246 | // be signed, larger than size_t, whatever. | |||
2247 | } | |||
2248 | ||||
2249 | FunctionDecl *OperatorNew = nullptr; | |||
2250 | FunctionDecl *OperatorDelete = nullptr; | |||
2251 | unsigned Alignment = | |||
2252 | AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); | |||
2253 | unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); | |||
2254 | bool PassAlignment = getLangOpts().AlignedAllocation && | |||
2255 | Alignment > NewAlignment; | |||
2256 | ||||
2257 | AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both; | |||
2258 | if (!AllocType->isDependentType() && | |||
2259 | !Expr::hasAnyTypeDependentArguments(PlacementArgs) && | |||
2260 | FindAllocationFunctions( | |||
2261 | StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope, | |||
2262 | AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs, | |||
2263 | OperatorNew, OperatorDelete)) | |||
2264 | return ExprError(); | |||
2265 | ||||
2266 | // If this is an array allocation, compute whether the usual array | |||
2267 | // deallocation function for the type has a size_t parameter. | |||
2268 | bool UsualArrayDeleteWantsSize = false; | |||
2269 | if (ArraySize && !AllocType->isDependentType()) | |||
2270 | UsualArrayDeleteWantsSize = | |||
2271 | doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); | |||
2272 | ||||
2273 | SmallVector<Expr *, 8> AllPlaceArgs; | |||
2274 | if (OperatorNew) { | |||
2275 | auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); | |||
2276 | VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction | |||
2277 | : VariadicDoesNotApply; | |||
2278 | ||||
2279 | // We've already converted the placement args, just fill in any default | |||
2280 | // arguments. Skip the first parameter because we don't have a corresponding | |||
2281 | // argument. Skip the second parameter too if we're passing in the | |||
2282 | // alignment; we've already filled it in. | |||
2283 | unsigned NumImplicitArgs = PassAlignment ? 2 : 1; | |||
2284 | if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, | |||
2285 | NumImplicitArgs, PlacementArgs, AllPlaceArgs, | |||
2286 | CallType)) | |||
2287 | return ExprError(); | |||
2288 | ||||
2289 | if (!AllPlaceArgs.empty()) | |||
2290 | PlacementArgs = AllPlaceArgs; | |||
2291 | ||||
2292 | // We would like to perform some checking on the given `operator new` call, | |||
2293 | // but the PlacementArgs does not contain the implicit arguments, | |||
2294 | // namely allocation size and maybe allocation alignment, | |||
2295 | // so we need to conjure them. | |||
2296 | ||||
2297 | QualType SizeTy = Context.getSizeType(); | |||
2298 | unsigned SizeTyWidth = Context.getTypeSize(SizeTy); | |||
2299 | ||||
2300 | llvm::APInt SingleEltSize( | |||
2301 | SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity()); | |||
2302 | ||||
2303 | // How many bytes do we want to allocate here? | |||
2304 | llvm::Optional<llvm::APInt> AllocationSize; | |||
2305 | if (!ArraySize && !AllocType->isDependentType()) { | |||
2306 | // For non-array operator new, we only want to allocate one element. | |||
2307 | AllocationSize = SingleEltSize; | |||
2308 | } else if (KnownArraySize && !AllocType->isDependentType()) { | |||
2309 | // For array operator new, only deal with static array size case. | |||
2310 | bool Overflow; | |||
2311 | AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) | |||
2312 | .umul_ov(SingleEltSize, Overflow); | |||
2313 | (void)Overflow; | |||
2314 | assert((static_cast <bool> (!Overflow && "Expected that all the overflows would have been handled already." ) ? void (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 2316, __extension__ __PRETTY_FUNCTION__ )) | |||
2315 | !Overflow &&(static_cast <bool> (!Overflow && "Expected that all the overflows would have been handled already." ) ? void (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 2316, __extension__ __PRETTY_FUNCTION__ )) | |||
2316 | "Expected that all the overflows would have been handled already.")(static_cast <bool> (!Overflow && "Expected that all the overflows would have been handled already." ) ? void (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 2316, __extension__ __PRETTY_FUNCTION__ )); | |||
2317 | } | |||
2318 | ||||
2319 | IntegerLiteral AllocationSizeLiteral( | |||
2320 | Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)), | |||
2321 | SizeTy, SourceLocation()); | |||
2322 | // Otherwise, if we failed to constant-fold the allocation size, we'll | |||
2323 | // just give up and pass-in something opaque, that isn't a null pointer. | |||
2324 | OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue, | |||
2325 | OK_Ordinary, /*SourceExpr=*/nullptr); | |||
2326 | ||||
2327 | // Let's synthesize the alignment argument in case we will need it. | |||
2328 | // Since we *really* want to allocate these on stack, this is slightly ugly | |||
2329 | // because there might not be a `std::align_val_t` type. | |||
2330 | EnumDecl *StdAlignValT = getStdAlignValT(); | |||
2331 | QualType AlignValT = | |||
2332 | StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy; | |||
2333 | IntegerLiteral AlignmentLiteral( | |||
2334 | Context, | |||
2335 | llvm::APInt(Context.getTypeSize(SizeTy), | |||
2336 | Alignment / Context.getCharWidth()), | |||
2337 | SizeTy, SourceLocation()); | |||
2338 | ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT, | |||
2339 | CK_IntegralCast, &AlignmentLiteral, | |||
2340 | VK_PRValue, FPOptionsOverride()); | |||
2341 | ||||
2342 | // Adjust placement args by prepending conjured size and alignment exprs. | |||
2343 | llvm::SmallVector<Expr *, 8> CallArgs; | |||
2344 | CallArgs.reserve(NumImplicitArgs + PlacementArgs.size()); | |||
2345 | CallArgs.emplace_back(AllocationSize | |||
2346 | ? static_cast<Expr *>(&AllocationSizeLiteral) | |||
2347 | : &OpaqueAllocationSize); | |||
2348 | if (PassAlignment) | |||
2349 | CallArgs.emplace_back(&DesiredAlignment); | |||
2350 | CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end()); | |||
2351 | ||||
2352 | DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs); | |||
2353 | ||||
2354 | checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs, | |||
2355 | /*IsMemberFunction=*/false, StartLoc, Range, CallType); | |||
2356 | ||||
2357 | // Warn if the type is over-aligned and is being allocated by (unaligned) | |||
2358 | // global operator new. | |||
2359 | if (PlacementArgs.empty() && !PassAlignment && | |||
2360 | (OperatorNew->isImplicit() || | |||
2361 | (OperatorNew->getBeginLoc().isValid() && | |||
2362 | getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) { | |||
2363 | if (Alignment > NewAlignment) | |||
2364 | Diag(StartLoc, diag::warn_overaligned_type) | |||
2365 | << AllocType | |||
2366 | << unsigned(Alignment / Context.getCharWidth()) | |||
2367 | << unsigned(NewAlignment / Context.getCharWidth()); | |||
2368 | } | |||
2369 | } | |||
2370 | ||||
2371 | // Array 'new' can't have any initializers except empty parentheses. | |||
2372 | // Initializer lists are also allowed, in C++11. Rely on the parser for the | |||
2373 | // dialect distinction. | |||
2374 | if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) { | |||
2375 | SourceRange InitRange(Exprs.front()->getBeginLoc(), | |||
2376 | Exprs.back()->getEndLoc()); | |||
2377 | Diag(StartLoc, diag::err_new_array_init_args) << InitRange; | |||
2378 | return ExprError(); | |||
2379 | } | |||
2380 | ||||
2381 | // If we can perform the initialization, and we've not already done so, | |||
2382 | // do it now. | |||
2383 | if (!AllocType->isDependentType() && | |||
2384 | !Expr::hasAnyTypeDependentArguments(Exprs)) { | |||
2385 | // The type we initialize is the complete type, including the array bound. | |||
2386 | QualType InitType; | |||
2387 | if (KnownArraySize) | |||
2388 | InitType = Context.getConstantArrayType( | |||
2389 | AllocType, | |||
2390 | llvm::APInt(Context.getTypeSize(Context.getSizeType()), | |||
2391 | *KnownArraySize), | |||
2392 | *ArraySize, ArrayType::Normal, 0); | |||
2393 | else if (ArraySize) | |||
2394 | InitType = | |||
2395 | Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0); | |||
2396 | else | |||
2397 | InitType = AllocType; | |||
2398 | ||||
2399 | InitializedEntity Entity | |||
2400 | = InitializedEntity::InitializeNew(StartLoc, InitType); | |||
2401 | InitializationSequence InitSeq(*this, Entity, Kind, Exprs); | |||
2402 | ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs); | |||
2403 | if (FullInit.isInvalid()) | |||
2404 | return ExprError(); | |||
2405 | ||||
2406 | // FullInit is our initializer; strip off CXXBindTemporaryExprs, because | |||
2407 | // we don't want the initialized object to be destructed. | |||
2408 | // FIXME: We should not create these in the first place. | |||
2409 | if (CXXBindTemporaryExpr *Binder = | |||
2410 | dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) | |||
2411 | FullInit = Binder->getSubExpr(); | |||
2412 | ||||
2413 | Initializer = FullInit.get(); | |||
2414 | ||||
2415 | // FIXME: If we have a KnownArraySize, check that the array bound of the | |||
2416 | // initializer is no greater than that constant value. | |||
2417 | ||||
2418 | if (ArraySize && !*ArraySize) { | |||
2419 | auto *CAT = Context.getAsConstantArrayType(Initializer->getType()); | |||
2420 | if (CAT) { | |||
2421 | // FIXME: Track that the array size was inferred rather than explicitly | |||
2422 | // specified. | |||
2423 | ArraySize = IntegerLiteral::Create( | |||
2424 | Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd()); | |||
2425 | } else { | |||
2426 | Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) | |||
2427 | << Initializer->getSourceRange(); | |||
2428 | } | |||
2429 | } | |||
2430 | } | |||
2431 | ||||
2432 | // Mark the new and delete operators as referenced. | |||
2433 | if (OperatorNew) { | |||
2434 | if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) | |||
2435 | return ExprError(); | |||
2436 | MarkFunctionReferenced(StartLoc, OperatorNew); | |||
2437 | } | |||
2438 | if (OperatorDelete) { | |||
2439 | if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) | |||
2440 | return ExprError(); | |||
2441 | MarkFunctionReferenced(StartLoc, OperatorDelete); | |||
2442 | } | |||
2443 | ||||
2444 | return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete, | |||
2445 | PassAlignment, UsualArrayDeleteWantsSize, | |||
2446 | PlacementArgs, TypeIdParens, ArraySize, initStyle, | |||
2447 | Initializer, ResultType, AllocTypeInfo, Range, | |||
2448 | DirectInitRange); | |||
2449 | } | |||
2450 | ||||
2451 | /// Checks that a type is suitable as the allocated type | |||
2452 | /// in a new-expression. | |||
2453 | bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, | |||
2454 | SourceRange R) { | |||
2455 | // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an | |||
2456 | // abstract class type or array thereof. | |||
2457 | if (AllocType->isFunctionType()) | |||
2458 | return Diag(Loc, diag::err_bad_new_type) | |||
2459 | << AllocType << 0 << R; | |||
2460 | else if (AllocType->isReferenceType()) | |||
2461 | return Diag(Loc, diag::err_bad_new_type) | |||
2462 | << AllocType << 1 << R; | |||
2463 | else if (!AllocType->isDependentType() && | |||
2464 | RequireCompleteSizedType( | |||
2465 | Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R)) | |||
2466 | return true; | |||
2467 | else if (RequireNonAbstractType(Loc, AllocType, | |||
2468 | diag::err_allocation_of_abstract_type)) | |||
2469 | return true; | |||
2470 | else if (AllocType->isVariablyModifiedType()) | |||
2471 | return Diag(Loc, diag::err_variably_modified_new_type) | |||
2472 | << AllocType; | |||
2473 | else if (AllocType.getAddressSpace() != LangAS::Default && | |||
2474 | !getLangOpts().OpenCLCPlusPlus) | |||
2475 | return Diag(Loc, diag::err_address_space_qualified_new) | |||
2476 | << AllocType.getUnqualifiedType() | |||
2477 | << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); | |||
2478 | else if (getLangOpts().ObjCAutoRefCount) { | |||
2479 | if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { | |||
2480 | QualType BaseAllocType = Context.getBaseElementType(AT); | |||
2481 | if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && | |||
2482 | BaseAllocType->isObjCLifetimeType()) | |||
2483 | return Diag(Loc, diag::err_arc_new_array_without_ownership) | |||
2484 | << BaseAllocType; | |||
2485 | } | |||
2486 | } | |||
2487 | ||||
2488 | return false; | |||
2489 | } | |||
2490 | ||||
2491 | static bool resolveAllocationOverload( | |||
2492 | Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, | |||
2493 | bool &PassAlignment, FunctionDecl *&Operator, | |||
2494 | OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { | |||
2495 | OverloadCandidateSet Candidates(R.getNameLoc(), | |||
2496 | OverloadCandidateSet::CSK_Normal); | |||
2497 | for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); | |||
2498 | Alloc != AllocEnd; ++Alloc) { | |||
2499 | // Even member operator new/delete are implicitly treated as | |||
2500 | // static, so don't use AddMemberCandidate. | |||
2501 | NamedDecl *D = (*Alloc)->getUnderlyingDecl(); | |||
2502 | ||||
2503 | if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { | |||
2504 | S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), | |||
2505 | /*ExplicitTemplateArgs=*/nullptr, Args, | |||
2506 | Candidates, | |||
2507 | /*SuppressUserConversions=*/false); | |||
2508 | continue; | |||
2509 | } | |||
2510 | ||||
2511 | FunctionDecl *Fn = cast<FunctionDecl>(D); | |||
2512 | S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, | |||
2513 | /*SuppressUserConversions=*/false); | |||
2514 | } | |||
2515 | ||||
2516 | // Do the resolution. | |||
2517 | OverloadCandidateSet::iterator Best; | |||
2518 | switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { | |||
2519 | case OR_Success: { | |||
2520 | // Got one! | |||
2521 | FunctionDecl *FnDecl = Best->Function; | |||
2522 | if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), | |||
2523 | Best->FoundDecl) == Sema::AR_inaccessible) | |||
2524 | return true; | |||
2525 | ||||
2526 | Operator = FnDecl; | |||
2527 | return false; | |||
2528 | } | |||
2529 | ||||
2530 | case OR_No_Viable_Function: | |||
2531 | // C++17 [expr.new]p13: | |||
2532 | // If no matching function is found and the allocated object type has | |||
2533 | // new-extended alignment, the alignment argument is removed from the | |||
2534 | // argument list, and overload resolution is performed again. | |||
2535 | if (PassAlignment) { | |||
2536 | PassAlignment = false; | |||
2537 | AlignArg = Args[1]; | |||
2538 | Args.erase(Args.begin() + 1); | |||
2539 | return resolveAllocationOverload(S, R, Range, Args, PassAlignment, | |||
2540 | Operator, &Candidates, AlignArg, | |||
2541 | Diagnose); | |||
2542 | } | |||
2543 | ||||
2544 | // MSVC will fall back on trying to find a matching global operator new | |||
2545 | // if operator new[] cannot be found. Also, MSVC will leak by not | |||
2546 | // generating a call to operator delete or operator delete[], but we | |||
2547 | // will not replicate that bug. | |||
2548 | // FIXME: Find out how this interacts with the std::align_val_t fallback | |||
2549 | // once MSVC implements it. | |||
2550 | if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && | |||
2551 | S.Context.getLangOpts().MSVCCompat) { | |||
2552 | R.clear(); | |||
2553 | R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); | |||
2554 | S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); | |||
2555 | // FIXME: This will give bad diagnostics pointing at the wrong functions. | |||
2556 | return resolveAllocationOverload(S, R, Range, Args, PassAlignment, | |||
2557 | Operator, /*Candidates=*/nullptr, | |||
2558 | /*AlignArg=*/nullptr, Diagnose); | |||
2559 | } | |||
2560 | ||||
2561 | if (Diagnose) { | |||
2562 | // If this is an allocation of the form 'new (p) X' for some object | |||
2563 | // pointer p (or an expression that will decay to such a pointer), | |||
2564 | // diagnose the missing inclusion of <new>. | |||
2565 | if (!R.isClassLookup() && Args.size() == 2 && | |||
2566 | (Args[1]->getType()->isObjectPointerType() || | |||
2567 | Args[1]->getType()->isArrayType())) { | |||
2568 | S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new) | |||
2569 | << R.getLookupName() << Range; | |||
2570 | // Listing the candidates is unlikely to be useful; skip it. | |||
2571 | return true; | |||
2572 | } | |||
2573 | ||||
2574 | // Finish checking all candidates before we note any. This checking can | |||
2575 | // produce additional diagnostics so can't be interleaved with our | |||
2576 | // emission of notes. | |||
2577 | // | |||
2578 | // For an aligned allocation, separately check the aligned and unaligned | |||
2579 | // candidates with their respective argument lists. | |||
2580 | SmallVector<OverloadCandidate*, 32> Cands; | |||
2581 | SmallVector<OverloadCandidate*, 32> AlignedCands; | |||
2582 | llvm::SmallVector<Expr*, 4> AlignedArgs; | |||
2583 | if (AlignedCandidates) { | |||
2584 | auto IsAligned = [](OverloadCandidate &C) { | |||
2585 | return C.Function->getNumParams() > 1 && | |||
2586 | C.Function->getParamDecl(1)->getType()->isAlignValT(); | |||
2587 | }; | |||
2588 | auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; | |||
2589 | ||||
2590 | AlignedArgs.reserve(Args.size() + 1); | |||
2591 | AlignedArgs.push_back(Args[0]); | |||
2592 | AlignedArgs.push_back(AlignArg); | |||
2593 | AlignedArgs.append(Args.begin() + 1, Args.end()); | |||
2594 | AlignedCands = AlignedCandidates->CompleteCandidates( | |||
2595 | S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned); | |||
2596 | ||||
2597 | Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, | |||
2598 | R.getNameLoc(), IsUnaligned); | |||
2599 | } else { | |||
2600 | Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, | |||
2601 | R.getNameLoc()); | |||
2602 | } | |||
2603 | ||||
2604 | S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) | |||
2605 | << R.getLookupName() << Range; | |||
2606 | if (AlignedCandidates) | |||
2607 | AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "", | |||
2608 | R.getNameLoc()); | |||
2609 | Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc()); | |||
2610 | } | |||
2611 | return true; | |||
2612 | ||||
2613 | case OR_Ambiguous: | |||
2614 | if (Diagnose) { | |||
2615 | Candidates.NoteCandidates( | |||
2616 | PartialDiagnosticAt(R.getNameLoc(), | |||
2617 | S.PDiag(diag::err_ovl_ambiguous_call) | |||
2618 | << R.getLookupName() << Range), | |||
2619 | S, OCD_AmbiguousCandidates, Args); | |||
2620 | } | |||
2621 | return true; | |||
2622 | ||||
2623 | case OR_Deleted: { | |||
2624 | if (Diagnose) { | |||
2625 | Candidates.NoteCandidates( | |||
2626 | PartialDiagnosticAt(R.getNameLoc(), | |||
2627 | S.PDiag(diag::err_ovl_deleted_call) | |||
2628 | << R.getLookupName() << Range), | |||
2629 | S, OCD_AllCandidates, Args); | |||
2630 | } | |||
2631 | return true; | |||
2632 | } | |||
2633 | } | |||
2634 | llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction" , "clang/lib/Sema/SemaExprCXX.cpp", 2634); | |||
2635 | } | |||
2636 | ||||
2637 | bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, | |||
2638 | AllocationFunctionScope NewScope, | |||
2639 | AllocationFunctionScope DeleteScope, | |||
2640 | QualType AllocType, bool IsArray, | |||
2641 | bool &PassAlignment, MultiExprArg PlaceArgs, | |||
2642 | FunctionDecl *&OperatorNew, | |||
2643 | FunctionDecl *&OperatorDelete, | |||
2644 | bool Diagnose) { | |||
2645 | // --- Choosing an allocation function --- | |||
2646 | // C++ 5.3.4p8 - 14 & 18 | |||
2647 | // 1) If looking in AFS_Global scope for allocation functions, only look in | |||
2648 | // the global scope. Else, if AFS_Class, only look in the scope of the | |||
2649 | // allocated class. If AFS_Both, look in both. | |||
2650 | // 2) If an array size is given, look for operator new[], else look for | |||
2651 | // operator new. | |||
2652 | // 3) The first argument is always size_t. Append the arguments from the | |||
2653 | // placement form. | |||
2654 | ||||
2655 | SmallVector<Expr*, 8> AllocArgs; | |||
2656 | AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); | |||
2657 | ||||
2658 | // We don't care about the actual value of these arguments. | |||
2659 | // FIXME: Should the Sema create the expression and embed it in the syntax | |||
2660 | // tree? Or should the consumer just recalculate the value? | |||
2661 | // FIXME: Using a dummy value will interact poorly with attribute enable_if. | |||
2662 | IntegerLiteral Size( | |||
2663 | Context, | |||
2664 | llvm::APInt::getZero( | |||
2665 | Context.getTargetInfo().getPointerWidth(LangAS::Default)), | |||
2666 | Context.getSizeType(), SourceLocation()); | |||
2667 | AllocArgs.push_back(&Size); | |||
2668 | ||||
2669 | QualType AlignValT = Context.VoidTy; | |||
2670 | if (PassAlignment) { | |||
2671 | DeclareGlobalNewDelete(); | |||
2672 | AlignValT = Context.getTypeDeclType(getStdAlignValT()); | |||
2673 | } | |||
2674 | CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); | |||
2675 | if (PassAlignment) | |||
2676 | AllocArgs.push_back(&Align); | |||
2677 | ||||
2678 | AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end()); | |||
2679 | ||||
2680 | // C++ [expr.new]p8: | |||
2681 | // If the allocated type is a non-array type, the allocation | |||
2682 | // function's name is operator new and the deallocation function's | |||
2683 | // name is operator delete. If the allocated type is an array | |||
2684 | // type, the allocation function's name is operator new[] and the | |||
2685 | // deallocation function's name is operator delete[]. | |||
2686 | DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( | |||
2687 | IsArray ? OO_Array_New : OO_New); | |||
2688 | ||||
2689 | QualType AllocElemType = Context.getBaseElementType(AllocType); | |||
2690 | ||||
2691 | // Find the allocation function. | |||
2692 | { | |||
2693 | LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); | |||
2694 | ||||
2695 | // C++1z [expr.new]p9: | |||
2696 | // If the new-expression begins with a unary :: operator, the allocation | |||
2697 | // function's name is looked up in the global scope. Otherwise, if the | |||
2698 | // allocated type is a class type T or array thereof, the allocation | |||
2699 | // function's name is looked up in the scope of T. | |||
2700 | if (AllocElemType->isRecordType() && NewScope != AFS_Global) | |||
2701 | LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); | |||
2702 | ||||
2703 | // We can see ambiguity here if the allocation function is found in | |||
2704 | // multiple base classes. | |||
2705 | if (R.isAmbiguous()) | |||
2706 | return true; | |||
2707 | ||||
2708 | // If this lookup fails to find the name, or if the allocated type is not | |||
2709 | // a class type, the allocation function's name is looked up in the | |||
2710 | // global scope. | |||
2711 | if (R.empty()) { | |||
2712 | if (NewScope == AFS_Class) | |||
2713 | return true; | |||
2714 | ||||
2715 | LookupQualifiedName(R, Context.getTranslationUnitDecl()); | |||
2716 | } | |||
2717 | ||||
2718 | if (getLangOpts().OpenCLCPlusPlus && R.empty()) { | |||
2719 | if (PlaceArgs.empty()) { | |||
2720 | Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; | |||
2721 | } else { | |||
2722 | Diag(StartLoc, diag::err_openclcxx_placement_new); | |||
2723 | } | |||
2724 | return true; | |||
2725 | } | |||
2726 | ||||
2727 | assert(!R.empty() && "implicitly declared allocation functions not found")(static_cast <bool> (!R.empty() && "implicitly declared allocation functions not found" ) ? void (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\"" , "clang/lib/Sema/SemaExprCXX.cpp", 2727, __extension__ __PRETTY_FUNCTION__ )); | |||
2728 | assert(!R.isAmbiguous() && "global allocation functions are ambiguous")(static_cast <bool> (!R.isAmbiguous() && "global allocation functions are ambiguous" ) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\"" , "clang/lib/Sema/SemaExprCXX.cpp", 2728, __extension__ __PRETTY_FUNCTION__ )); | |||
2729 | ||||
2730 | // We do our own custom access checks below. | |||
2731 | R.suppressDiagnostics(); | |||
2732 | ||||
2733 | if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, | |||
2734 | OperatorNew, /*Candidates=*/nullptr, | |||
2735 | /*AlignArg=*/nullptr, Diagnose)) | |||
2736 | return true; | |||
2737 | } | |||
2738 | ||||
2739 | // We don't need an operator delete if we're running under -fno-exceptions. | |||
2740 | if (!getLangOpts().Exceptions) { | |||
2741 | OperatorDelete = nullptr; | |||
2742 | return false; | |||
2743 | } | |||
2744 | ||||
2745 | // Note, the name of OperatorNew might have been changed from array to | |||
2746 | // non-array by resolveAllocationOverload. | |||
2747 | DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( | |||
2748 | OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New | |||
2749 | ? OO_Array_Delete | |||
2750 | : OO_Delete); | |||
2751 | ||||
2752 | // C++ [expr.new]p19: | |||
2753 | // | |||
2754 | // If the new-expression begins with a unary :: operator, the | |||
2755 | // deallocation function's name is looked up in the global | |||
2756 | // scope. Otherwise, if the allocated type is a class type T or an | |||
2757 | // array thereof, the deallocation function's name is looked up in | |||
2758 | // the scope of T. If this lookup fails to find the name, or if | |||
2759 | // the allocated type is not a class type or array thereof, the | |||
2760 | // deallocation function's name is looked up in the global scope. | |||
2761 | LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); | |||
2762 | if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) { | |||
2763 | auto *RD = | |||
2764 | cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl()); | |||
2765 | LookupQualifiedName(FoundDelete, RD); | |||
2766 | } | |||
2767 | if (FoundDelete.isAmbiguous()) | |||
2768 | return true; // FIXME: clean up expressions? | |||
2769 | ||||
2770 | // Filter out any destroying operator deletes. We can't possibly call such a | |||
2771 | // function in this context, because we're handling the case where the object | |||
2772 | // was not successfully constructed. | |||
2773 | // FIXME: This is not covered by the language rules yet. | |||
2774 | { | |||
2775 | LookupResult::Filter Filter = FoundDelete.makeFilter(); | |||
2776 | while (Filter.hasNext()) { | |||
2777 | auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl()); | |||
2778 | if (FD && FD->isDestroyingOperatorDelete()) | |||
2779 | Filter.erase(); | |||
2780 | } | |||
2781 | Filter.done(); | |||
2782 | } | |||
2783 | ||||
2784 | bool FoundGlobalDelete = FoundDelete.empty(); | |||
2785 | if (FoundDelete.empty()) { | |||
2786 | FoundDelete.clear(LookupOrdinaryName); | |||
2787 | ||||
2788 | if (DeleteScope == AFS_Class) | |||
2789 | return true; | |||
2790 | ||||
2791 | DeclareGlobalNewDelete(); | |||
2792 | LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); | |||
2793 | } | |||
2794 | ||||
2795 | FoundDelete.suppressDiagnostics(); | |||
2796 | ||||
2797 | SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; | |||
2798 | ||||
2799 | // Whether we're looking for a placement operator delete is dictated | |||
2800 | // by whether we selected a placement operator new, not by whether | |||
2801 | // we had explicit placement arguments. This matters for things like | |||
2802 | // struct A { void *operator new(size_t, int = 0); ... }; | |||
2803 | // A *a = new A() | |||
2804 | // | |||
2805 | // We don't have any definition for what a "placement allocation function" | |||
2806 | // is, but we assume it's any allocation function whose | |||
2807 | // parameter-declaration-clause is anything other than (size_t). | |||
2808 | // | |||
2809 | // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? | |||
2810 | // This affects whether an exception from the constructor of an overaligned | |||
2811 | // type uses the sized or non-sized form of aligned operator delete. | |||
2812 | bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || | |||
2813 | OperatorNew->isVariadic(); | |||
2814 | ||||
2815 | if (isPlacementNew) { | |||
2816 | // C++ [expr.new]p20: | |||
2817 | // A declaration of a placement deallocation function matches the | |||
2818 | // declaration of a placement allocation function if it has the | |||
2819 | // same number of parameters and, after parameter transformations | |||
2820 | // (8.3.5), all parameter types except the first are | |||
2821 | // identical. [...] | |||
2822 | // | |||
2823 | // To perform this comparison, we compute the function type that | |||
2824 | // the deallocation function should have, and use that type both | |||
2825 | // for template argument deduction and for comparison purposes. | |||
2826 | QualType ExpectedFunctionType; | |||
2827 | { | |||
2828 | auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); | |||
2829 | ||||
2830 | SmallVector<QualType, 4> ArgTypes; | |||
2831 | ArgTypes.push_back(Context.VoidPtrTy); | |||
2832 | for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) | |||
2833 | ArgTypes.push_back(Proto->getParamType(I)); | |||
2834 | ||||
2835 | FunctionProtoType::ExtProtoInfo EPI; | |||
2836 | // FIXME: This is not part of the standard's rule. | |||
2837 | EPI.Variadic = Proto->isVariadic(); | |||
2838 | ||||
2839 | ExpectedFunctionType | |||
2840 | = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); | |||
2841 | } | |||
2842 | ||||
2843 | for (LookupResult::iterator D = FoundDelete.begin(), | |||
2844 | DEnd = FoundDelete.end(); | |||
2845 | D != DEnd; ++D) { | |||
2846 | FunctionDecl *Fn = nullptr; | |||
2847 | if (FunctionTemplateDecl *FnTmpl = | |||
2848 | dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { | |||
2849 | // Perform template argument deduction to try to match the | |||
2850 | // expected function type. | |||
2851 | TemplateDeductionInfo Info(StartLoc); | |||
2852 | if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, | |||
2853 | Info)) | |||
2854 | continue; | |||
2855 | } else | |||
2856 | Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); | |||
2857 | ||||
2858 | if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(), | |||
2859 | ExpectedFunctionType, | |||
2860 | /*AdjustExcpetionSpec*/true), | |||
2861 | ExpectedFunctionType)) | |||
2862 | Matches.push_back(std::make_pair(D.getPair(), Fn)); | |||
2863 | } | |||
2864 | ||||
2865 | if (getLangOpts().CUDA) | |||
2866 | EraseUnwantedCUDAMatches(getCurFunctionDecl(/*AllowLambda=*/true), | |||
2867 | Matches); | |||
2868 | } else { | |||
2869 | // C++1y [expr.new]p22: | |||
2870 | // For a non-placement allocation function, the normal deallocation | |||
2871 | // function lookup is used | |||
2872 | // | |||
2873 | // Per [expr.delete]p10, this lookup prefers a member operator delete | |||
2874 | // without a size_t argument, but prefers a non-member operator delete | |||
2875 | // with a size_t where possible (which it always is in this case). | |||
2876 | llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; | |||
2877 | UsualDeallocFnInfo Selected = resolveDeallocationOverload( | |||
2878 | *this, FoundDelete, /*WantSize*/ FoundGlobalDelete, | |||
2879 | /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType), | |||
2880 | &BestDeallocFns); | |||
2881 | if (Selected) | |||
2882 | Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); | |||
2883 | else { | |||
2884 | // If we failed to select an operator, all remaining functions are viable | |||
2885 | // but ambiguous. | |||
2886 | for (auto Fn : BestDeallocFns) | |||
2887 | Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); | |||
2888 | } | |||
2889 | } | |||
2890 | ||||
2891 | // C++ [expr.new]p20: | |||
2892 | // [...] If the lookup finds a single matching deallocation | |||
2893 | // function, that function will be called; otherwise, no | |||
2894 | // deallocation function will be called. | |||
2895 | if (Matches.size() == 1) { | |||
2896 | OperatorDelete = Matches[0].second; | |||
2897 | ||||
2898 | // C++1z [expr.new]p23: | |||
2899 | // If the lookup finds a usual deallocation function (3.7.4.2) | |||
2900 | // with a parameter of type std::size_t and that function, considered | |||
2901 | // as a placement deallocation function, would have been | |||
2902 | // selected as a match for the allocation function, the program | |||
2903 | // is ill-formed. | |||
2904 | if (getLangOpts().CPlusPlus11 && isPlacementNew && | |||
2905 | isNonPlacementDeallocationFunction(*this, OperatorDelete)) { | |||
2906 | UsualDeallocFnInfo Info(*this, | |||
2907 | DeclAccessPair::make(OperatorDelete, AS_public)); | |||
2908 | // Core issue, per mail to core reflector, 2016-10-09: | |||
2909 | // If this is a member operator delete, and there is a corresponding | |||
2910 | // non-sized member operator delete, this isn't /really/ a sized | |||
2911 | // deallocation function, it just happens to have a size_t parameter. | |||
2912 | bool IsSizedDelete = Info.HasSizeT; | |||
2913 | if (IsSizedDelete && !FoundGlobalDelete) { | |||
2914 | auto NonSizedDelete = | |||
2915 | resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false, | |||
2916 | /*WantAlign*/Info.HasAlignValT); | |||
2917 | if (NonSizedDelete && !NonSizedDelete.HasSizeT && | |||
2918 | NonSizedDelete.HasAlignValT == Info.HasAlignValT) | |||
2919 | IsSizedDelete = false; | |||
2920 | } | |||
2921 | ||||
2922 | if (IsSizedDelete) { | |||
2923 | SourceRange R = PlaceArgs.empty() | |||
2924 | ? SourceRange() | |||
2925 | : SourceRange(PlaceArgs.front()->getBeginLoc(), | |||
2926 | PlaceArgs.back()->getEndLoc()); | |||
2927 | Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; | |||
2928 | if (!OperatorDelete->isImplicit()) | |||
2929 | Diag(OperatorDelete->getLocation(), diag::note_previous_decl) | |||
2930 | << DeleteName; | |||
2931 | } | |||
2932 | } | |||
2933 | ||||
2934 | CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), | |||
2935 | Matches[0].first); | |||
2936 | } else if (!Matches.empty()) { | |||
2937 | // We found multiple suitable operators. Per [expr.new]p20, that means we | |||
2938 | // call no 'operator delete' function, but we should at least warn the user. | |||
2939 | // FIXME: Suppress this warning if the construction cannot throw. | |||
2940 | Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) | |||
2941 | << DeleteName << AllocElemType; | |||
2942 | ||||
2943 | for (auto &Match : Matches) | |||
2944 | Diag(Match.second->getLocation(), | |||
2945 | diag::note_member_declared_here) << DeleteName; | |||
2946 | } | |||
2947 | ||||
2948 | return false; | |||
2949 | } | |||
2950 | ||||
2951 | /// DeclareGlobalNewDelete - Declare the global forms of operator new and | |||
2952 | /// delete. These are: | |||
2953 | /// @code | |||
2954 | /// // C++03: | |||
2955 | /// void* operator new(std::size_t) throw(std::bad_alloc); | |||
2956 | /// void* operator new[](std::size_t) throw(std::bad_alloc); | |||
2957 | /// void operator delete(void *) throw(); | |||
2958 | /// void operator delete[](void *) throw(); | |||
2959 | /// // C++11: | |||
2960 | /// void* operator new(std::size_t); | |||
2961 | /// void* operator new[](std::size_t); | |||
2962 | /// void operator delete(void *) noexcept; | |||
2963 | /// void operator delete[](void *) noexcept; | |||
2964 | /// // C++1y: | |||
2965 | /// void* operator new(std::size_t); | |||
2966 | /// void* operator new[](std::size_t); | |||
2967 | /// void operator delete(void *) noexcept; | |||
2968 | /// void operator delete[](void *) noexcept; | |||
2969 | /// void operator delete(void *, std::size_t) noexcept; | |||
2970 | /// void operator delete[](void *, std::size_t) noexcept; | |||
2971 | /// @endcode | |||
2972 | /// Note that the placement and nothrow forms of new are *not* implicitly | |||
2973 | /// declared. Their use requires including \<new\>. | |||
2974 | void Sema::DeclareGlobalNewDelete() { | |||
2975 | if (GlobalNewDeleteDeclared) | |||
2976 | return; | |||
2977 | ||||
2978 | // The implicitly declared new and delete operators | |||
2979 | // are not supported in OpenCL. | |||
2980 | if (getLangOpts().OpenCLCPlusPlus) | |||
2981 | return; | |||
2982 | ||||
2983 | // C++ [basic.stc.dynamic.general]p2: | |||
2984 | // The library provides default definitions for the global allocation | |||
2985 | // and deallocation functions. Some global allocation and deallocation | |||
2986 | // functions are replaceable ([new.delete]); these are attached to the | |||
2987 | // global module ([module.unit]). | |||
2988 | if (getLangOpts().CPlusPlusModules && getCurrentModule()) | |||
2989 | PushGlobalModuleFragment(SourceLocation(), /*IsImplicit=*/true); | |||
2990 | ||||
2991 | // C++ [basic.std.dynamic]p2: | |||
2992 | // [...] The following allocation and deallocation functions (18.4) are | |||
2993 | // implicitly declared in global scope in each translation unit of a | |||
2994 | // program | |||
2995 | // | |||
2996 | // C++03: | |||
2997 | // void* operator new(std::size_t) throw(std::bad_alloc); | |||
2998 | // void* operator new[](std::size_t) throw(std::bad_alloc); | |||
2999 | // void operator delete(void*) throw(); | |||
3000 | // void operator delete[](void*) throw(); | |||
3001 | // C++11: | |||
3002 | // void* operator new(std::size_t); | |||
3003 | // void* operator new[](std::size_t); | |||
3004 | // void operator delete(void*) noexcept; | |||
3005 | // void operator delete[](void*) noexcept; | |||
3006 | // C++1y: | |||
3007 | // void* operator new(std::size_t); | |||
3008 | // void* operator new[](std::size_t); | |||
3009 | // void operator delete(void*) noexcept; | |||
3010 | // void operator delete[](void*) noexcept; | |||
3011 | // void operator delete(void*, std::size_t) noexcept; | |||
3012 | // void operator delete[](void*, std::size_t) noexcept; | |||
3013 | // | |||
3014 | // These implicit declarations introduce only the function names operator | |||
3015 | // new, operator new[], operator delete, operator delete[]. | |||
3016 | // | |||
3017 | // Here, we need to refer to std::bad_alloc, so we will implicitly declare | |||
3018 | // "std" or "bad_alloc" as necessary to form the exception specification. | |||
3019 | // However, we do not make these implicit declarations visible to name | |||
3020 | // lookup. | |||
3021 | if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { | |||
3022 | // The "std::bad_alloc" class has not yet been declared, so build it | |||
3023 | // implicitly. | |||
3024 | StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, | |||
3025 | getOrCreateStdNamespace(), | |||
3026 | SourceLocation(), SourceLocation(), | |||
3027 | &PP.getIdentifierTable().get("bad_alloc"), | |||
3028 | nullptr); | |||
3029 | getStdBadAlloc()->setImplicit(true); | |||
3030 | ||||
3031 | // The implicitly declared "std::bad_alloc" should live in global module | |||
3032 | // fragment. | |||
3033 | if (GlobalModuleFragment) { | |||
3034 | getStdBadAlloc()->setModuleOwnershipKind( | |||
3035 | Decl::ModuleOwnershipKind::ReachableWhenImported); | |||
3036 | getStdBadAlloc()->setLocalOwningModule(GlobalModuleFragment); | |||
3037 | } | |||
3038 | } | |||
3039 | if (!StdAlignValT && getLangOpts().AlignedAllocation) { | |||
3040 | // The "std::align_val_t" enum class has not yet been declared, so build it | |||
3041 | // implicitly. | |||
3042 | auto *AlignValT = EnumDecl::Create( | |||
3043 | Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), | |||
3044 | &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); | |||
3045 | ||||
3046 | // The implicitly declared "std::align_val_t" should live in global module | |||
3047 | // fragment. | |||
3048 | if (GlobalModuleFragment) { | |||
3049 | AlignValT->setModuleOwnershipKind( | |||
3050 | Decl::ModuleOwnershipKind::ReachableWhenImported); | |||
3051 | AlignValT->setLocalOwningModule(GlobalModuleFragment); | |||
3052 | } | |||
3053 | ||||
3054 | AlignValT->setIntegerType(Context.getSizeType()); | |||
3055 | AlignValT->setPromotionType(Context.getSizeType()); | |||
3056 | AlignValT->setImplicit(true); | |||
3057 | ||||
3058 | StdAlignValT = AlignValT; | |||
3059 | } | |||
3060 | ||||
3061 | GlobalNewDeleteDeclared = true; | |||
3062 | ||||
3063 | QualType VoidPtr = Context.getPointerType(Context.VoidTy); | |||
3064 | QualType SizeT = Context.getSizeType(); | |||
3065 | ||||
3066 | auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, | |||
3067 | QualType Return, QualType Param) { | |||
3068 | llvm::SmallVector<QualType, 3> Params; | |||
3069 | Params.push_back(Param); | |||
3070 | ||||
3071 | // Create up to four variants of the function (sized/aligned). | |||
3072 | bool HasSizedVariant = getLangOpts().SizedDeallocation && | |||
3073 | (Kind == OO_Delete || Kind == OO_Array_Delete); | |||
3074 | bool HasAlignedVariant = getLangOpts().AlignedAllocation; | |||
3075 | ||||
3076 | int NumSizeVariants = (HasSizedVariant ? 2 : 1); | |||
3077 | int NumAlignVariants = (HasAlignedVariant ? 2 : 1); | |||
3078 | for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { | |||
3079 | if (Sized) | |||
3080 | Params.push_back(SizeT); | |||
3081 | ||||
3082 | for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { | |||
3083 | if (Aligned) | |||
3084 | Params.push_back(Context.getTypeDeclType(getStdAlignValT())); | |||
3085 | ||||
3086 | DeclareGlobalAllocationFunction( | |||
3087 | Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); | |||
3088 | ||||
3089 | if (Aligned) | |||
3090 | Params.pop_back(); | |||
3091 | } | |||
3092 | } | |||
3093 | }; | |||
3094 | ||||
3095 | DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); | |||
3096 | DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); | |||
3097 | DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); | |||
3098 | DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); | |||
3099 | ||||
3100 | if (getLangOpts().CPlusPlusModules && getCurrentModule()) | |||
3101 | PopGlobalModuleFragment(); | |||
3102 | } | |||
3103 | ||||
3104 | /// DeclareGlobalAllocationFunction - Declares a single implicit global | |||
3105 | /// allocation function if it doesn't already exist. | |||
3106 | void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, | |||
3107 | QualType Return, | |||
3108 | ArrayRef<QualType> Params) { | |||
3109 | DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); | |||
3110 | ||||
3111 | // Check if this function is already declared. | |||
3112 | DeclContext::lookup_result R = GlobalCtx->lookup(Name); | |||
3113 | for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); | |||
3114 | Alloc != AllocEnd; ++Alloc) { | |||
3115 | // Only look at non-template functions, as it is the predefined, | |||
3116 | // non-templated allocation function we are trying to declare here. | |||
3117 | if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { | |||
3118 | if (Func->getNumParams() == Params.size()) { | |||
3119 | llvm::SmallVector<QualType, 3> FuncParams; | |||
3120 | for (auto *P : Func->parameters()) | |||
3121 | FuncParams.push_back( | |||
3122 | Context.getCanonicalType(P->getType().getUnqualifiedType())); | |||
3123 | if (llvm::ArrayRef(FuncParams) == Params) { | |||
3124 | // Make the function visible to name lookup, even if we found it in | |||
3125 | // an unimported module. It either is an implicitly-declared global | |||
3126 | // allocation function, or is suppressing that function. | |||
3127 | Func->setVisibleDespiteOwningModule(); | |||
3128 | return; | |||
3129 | } | |||
3130 | } | |||
3131 | } | |||
3132 | } | |||
3133 | ||||
3134 | FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( | |||
3135 | /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); | |||
3136 | ||||
3137 | QualType BadAllocType; | |||
3138 | bool HasBadAllocExceptionSpec | |||
3139 | = (Name.getCXXOverloadedOperator() == OO_New || | |||
3140 | Name.getCXXOverloadedOperator() == OO_Array_New); | |||
3141 | if (HasBadAllocExceptionSpec) { | |||
3142 | if (!getLangOpts().CPlusPlus11) { | |||
3143 | BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); | |||
3144 | assert(StdBadAlloc && "Must have std::bad_alloc declared")(static_cast <bool> (StdBadAlloc && "Must have std::bad_alloc declared" ) ? void (0) : __assert_fail ("StdBadAlloc && \"Must have std::bad_alloc declared\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3144, __extension__ __PRETTY_FUNCTION__ )); | |||
3145 | EPI.ExceptionSpec.Type = EST_Dynamic; | |||
3146 | EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType); | |||
3147 | } | |||
3148 | if (getLangOpts().NewInfallible) { | |||
3149 | EPI.ExceptionSpec.Type = EST_DynamicNone; | |||
3150 | } | |||
3151 | } else { | |||
3152 | EPI.ExceptionSpec = | |||
3153 | getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; | |||
3154 | } | |||
3155 | ||||
3156 | auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { | |||
3157 | QualType FnType = Context.getFunctionType(Return, Params, EPI); | |||
3158 | FunctionDecl *Alloc = FunctionDecl::Create( | |||
3159 | Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType, | |||
3160 | /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false, | |||
3161 | true); | |||
3162 | Alloc->setImplicit(); | |||
3163 | // Global allocation functions should always be visible. | |||
3164 | Alloc->setVisibleDespiteOwningModule(); | |||
3165 | ||||
3166 | if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible) | |||
3167 | Alloc->addAttr( | |||
3168 | ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation())); | |||
3169 | ||||
3170 | // C++ [basic.stc.dynamic.general]p2: | |||
3171 | // The library provides default definitions for the global allocation | |||
3172 | // and deallocation functions. Some global allocation and deallocation | |||
3173 | // functions are replaceable ([new.delete]); these are attached to the | |||
3174 | // global module ([module.unit]). | |||
3175 | // | |||
3176 | // In the language wording, these functions are attched to the global | |||
3177 | // module all the time. But in the implementation, the global module | |||
3178 | // is only meaningful when we're in a module unit. So here we attach | |||
3179 | // these allocation functions to global module conditionally. | |||
3180 | if (GlobalModuleFragment) { | |||
3181 | Alloc->setModuleOwnershipKind( | |||
3182 | Decl::ModuleOwnershipKind::ReachableWhenImported); | |||
3183 | Alloc->setLocalOwningModule(GlobalModuleFragment); | |||
3184 | } | |||
3185 | ||||
3186 | Alloc->addAttr(VisibilityAttr::CreateImplicit( | |||
3187 | Context, LangOpts.GlobalAllocationFunctionVisibilityHidden | |||
3188 | ? VisibilityAttr::Hidden | |||
3189 | : VisibilityAttr::Default)); | |||
3190 | ||||
3191 | llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; | |||
3192 | for (QualType T : Params) { | |||
3193 | ParamDecls.push_back(ParmVarDecl::Create( | |||
3194 | Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, | |||
3195 | /*TInfo=*/nullptr, SC_None, nullptr)); | |||
3196 | ParamDecls.back()->setImplicit(); | |||
3197 | } | |||
3198 | Alloc->setParams(ParamDecls); | |||
3199 | if (ExtraAttr) | |||
3200 | Alloc->addAttr(ExtraAttr); | |||
3201 | AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc); | |||
3202 | Context.getTranslationUnitDecl()->addDecl(Alloc); | |||
3203 | IdResolver.tryAddTopLevelDecl(Alloc, Name); | |||
3204 | }; | |||
3205 | ||||
3206 | if (!LangOpts.CUDA) | |||
3207 | CreateAllocationFunctionDecl(nullptr); | |||
3208 | else { | |||
3209 | // Host and device get their own declaration so each can be | |||
3210 | // defined or re-declared independently. | |||
3211 | CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); | |||
3212 | CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); | |||
3213 | } | |||
3214 | } | |||
3215 | ||||
3216 | FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, | |||
3217 | bool CanProvideSize, | |||
3218 | bool Overaligned, | |||
3219 | DeclarationName Name) { | |||
3220 | DeclareGlobalNewDelete(); | |||
3221 | ||||
3222 | LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); | |||
3223 | LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); | |||
3224 | ||||
3225 | // FIXME: It's possible for this to result in ambiguity, through a | |||
3226 | // user-declared variadic operator delete or the enable_if attribute. We | |||
3227 | // should probably not consider those cases to be usual deallocation | |||
3228 | // functions. But for now we just make an arbitrary choice in that case. | |||
3229 | auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, | |||
3230 | Overaligned); | |||
3231 | assert(Result.FD && "operator delete missing from global scope?")(static_cast <bool> (Result.FD && "operator delete missing from global scope?" ) ? void (0) : __assert_fail ("Result.FD && \"operator delete missing from global scope?\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3231, __extension__ __PRETTY_FUNCTION__ )); | |||
3232 | return Result.FD; | |||
3233 | } | |||
3234 | ||||
3235 | FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, | |||
3236 | CXXRecordDecl *RD) { | |||
3237 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete); | |||
3238 | ||||
3239 | FunctionDecl *OperatorDelete = nullptr; | |||
3240 | if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) | |||
3241 | return nullptr; | |||
3242 | if (OperatorDelete) | |||
3243 | return OperatorDelete; | |||
3244 | ||||
3245 | // If there's no class-specific operator delete, look up the global | |||
3246 | // non-array delete. | |||
3247 | return FindUsualDeallocationFunction( | |||
3248 | Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), | |||
3249 | Name); | |||
3250 | } | |||
3251 | ||||
3252 | bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, | |||
3253 | DeclarationName Name, | |||
3254 | FunctionDecl *&Operator, bool Diagnose, | |||
3255 | bool WantSize, bool WantAligned) { | |||
3256 | LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); | |||
3257 | // Try to find operator delete/operator delete[] in class scope. | |||
3258 | LookupQualifiedName(Found, RD); | |||
3259 | ||||
3260 | if (Found.isAmbiguous()) | |||
3261 | return true; | |||
3262 | ||||
3263 | Found.suppressDiagnostics(); | |||
3264 | ||||
3265 | bool Overaligned = | |||
3266 | WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD)); | |||
3267 | ||||
3268 | // C++17 [expr.delete]p10: | |||
3269 | // If the deallocation functions have class scope, the one without a | |||
3270 | // parameter of type std::size_t is selected. | |||
3271 | llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; | |||
3272 | resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize, | |||
3273 | /*WantAlign*/ Overaligned, &Matches); | |||
3274 | ||||
3275 | // If we could find an overload, use it. | |||
3276 | if (Matches.size() == 1) { | |||
3277 | Operator = cast<CXXMethodDecl>(Matches[0].FD); | |||
3278 | ||||
3279 | // FIXME: DiagnoseUseOfDecl? | |||
3280 | if (Operator->isDeleted()) { | |||
3281 | if (Diagnose) { | |||
3282 | Diag(StartLoc, diag::err_deleted_function_use); | |||
3283 | NoteDeletedFunction(Operator); | |||
3284 | } | |||
3285 | return true; | |||
3286 | } | |||
3287 | ||||
3288 | if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), | |||
3289 | Matches[0].Found, Diagnose) == AR_inaccessible) | |||
3290 | return true; | |||
3291 | ||||
3292 | return false; | |||
3293 | } | |||
3294 | ||||
3295 | // We found multiple suitable operators; complain about the ambiguity. | |||
3296 | // FIXME: The standard doesn't say to do this; it appears that the intent | |||
3297 | // is that this should never happen. | |||
3298 | if (!Matches.empty()) { | |||
3299 | if (Diagnose) { | |||
3300 | Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) | |||
3301 | << Name << RD; | |||
3302 | for (auto &Match : Matches) | |||
3303 | Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; | |||
3304 | } | |||
3305 | return true; | |||
3306 | } | |||
3307 | ||||
3308 | // We did find operator delete/operator delete[] declarations, but | |||
3309 | // none of them were suitable. | |||
3310 | if (!Found.empty()) { | |||
3311 | if (Diagnose) { | |||
3312 | Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) | |||
3313 | << Name << RD; | |||
3314 | ||||
3315 | for (NamedDecl *D : Found) | |||
3316 | Diag(D->getUnderlyingDecl()->getLocation(), | |||
3317 | diag::note_member_declared_here) << Name; | |||
3318 | } | |||
3319 | return true; | |||
3320 | } | |||
3321 | ||||
3322 | Operator = nullptr; | |||
3323 | return false; | |||
3324 | } | |||
3325 | ||||
3326 | namespace { | |||
3327 | /// Checks whether delete-expression, and new-expression used for | |||
3328 | /// initializing deletee have the same array form. | |||
3329 | class MismatchingNewDeleteDetector { | |||
3330 | public: | |||
3331 | enum MismatchResult { | |||
3332 | /// Indicates that there is no mismatch or a mismatch cannot be proven. | |||
3333 | NoMismatch, | |||
3334 | /// Indicates that variable is initialized with mismatching form of \a new. | |||
3335 | VarInitMismatches, | |||
3336 | /// Indicates that member is initialized with mismatching form of \a new. | |||
3337 | MemberInitMismatches, | |||
3338 | /// Indicates that 1 or more constructors' definitions could not been | |||
3339 | /// analyzed, and they will be checked again at the end of translation unit. | |||
3340 | AnalyzeLater | |||
3341 | }; | |||
3342 | ||||
3343 | /// \param EndOfTU True, if this is the final analysis at the end of | |||
3344 | /// translation unit. False, if this is the initial analysis at the point | |||
3345 | /// delete-expression was encountered. | |||
3346 | explicit MismatchingNewDeleteDetector(bool EndOfTU) | |||
3347 | : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), | |||
3348 | HasUndefinedConstructors(false) {} | |||
3349 | ||||
3350 | /// Checks whether pointee of a delete-expression is initialized with | |||
3351 | /// matching form of new-expression. | |||
3352 | /// | |||
3353 | /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the | |||
3354 | /// point where delete-expression is encountered, then a warning will be | |||
3355 | /// issued immediately. If return value is \c AnalyzeLater at the point where | |||
3356 | /// delete-expression is seen, then member will be analyzed at the end of | |||
3357 | /// translation unit. \c AnalyzeLater is returned iff at least one constructor | |||
3358 | /// couldn't be analyzed. If at least one constructor initializes the member | |||
3359 | /// with matching type of new, the return value is \c NoMismatch. | |||
3360 | MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); | |||
3361 | /// Analyzes a class member. | |||
3362 | /// \param Field Class member to analyze. | |||
3363 | /// \param DeleteWasArrayForm Array form-ness of the delete-expression used | |||
3364 | /// for deleting the \p Field. | |||
3365 | MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); | |||
3366 | FieldDecl *Field; | |||
3367 | /// List of mismatching new-expressions used for initialization of the pointee | |||
3368 | llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; | |||
3369 | /// Indicates whether delete-expression was in array form. | |||
3370 | bool IsArrayForm; | |||
3371 | ||||
3372 | private: | |||
3373 | const bool EndOfTU; | |||
3374 | /// Indicates that there is at least one constructor without body. | |||
3375 | bool HasUndefinedConstructors; | |||
3376 | /// Returns \c CXXNewExpr from given initialization expression. | |||
3377 | /// \param E Expression used for initializing pointee in delete-expression. | |||
3378 | /// E can be a single-element \c InitListExpr consisting of new-expression. | |||
3379 | const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); | |||
3380 | /// Returns whether member is initialized with mismatching form of | |||
3381 | /// \c new either by the member initializer or in-class initialization. | |||
3382 | /// | |||
3383 | /// If bodies of all constructors are not visible at the end of translation | |||
3384 | /// unit or at least one constructor initializes member with the matching | |||
3385 | /// form of \c new, mismatch cannot be proven, and this function will return | |||
3386 | /// \c NoMismatch. | |||
3387 | MismatchResult analyzeMemberExpr(const MemberExpr *ME); | |||
3388 | /// Returns whether variable is initialized with mismatching form of | |||
3389 | /// \c new. | |||
3390 | /// | |||
3391 | /// If variable is initialized with matching form of \c new or variable is not | |||
3392 | /// initialized with a \c new expression, this function will return true. | |||
3393 | /// If variable is initialized with mismatching form of \c new, returns false. | |||
3394 | /// \param D Variable to analyze. | |||
3395 | bool hasMatchingVarInit(const DeclRefExpr *D); | |||
3396 | /// Checks whether the constructor initializes pointee with mismatching | |||
3397 | /// form of \c new. | |||
3398 | /// | |||
3399 | /// Returns true, if member is initialized with matching form of \c new in | |||
3400 | /// member initializer list. Returns false, if member is initialized with the | |||
3401 | /// matching form of \c new in this constructor's initializer or given | |||
3402 | /// constructor isn't defined at the point where delete-expression is seen, or | |||
3403 | /// member isn't initialized by the constructor. | |||
3404 | bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); | |||
3405 | /// Checks whether member is initialized with matching form of | |||
3406 | /// \c new in member initializer list. | |||
3407 | bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); | |||
3408 | /// Checks whether member is initialized with mismatching form of \c new by | |||
3409 | /// in-class initializer. | |||
3410 | MismatchResult analyzeInClassInitializer(); | |||
3411 | }; | |||
3412 | } | |||
3413 | ||||
3414 | MismatchingNewDeleteDetector::MismatchResult | |||
3415 | MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { | |||
3416 | NewExprs.clear(); | |||
3417 | assert(DE && "Expected delete-expression")(static_cast <bool> (DE && "Expected delete-expression" ) ? void (0) : __assert_fail ("DE && \"Expected delete-expression\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3417, __extension__ __PRETTY_FUNCTION__ )); | |||
3418 | IsArrayForm = DE->isArrayForm(); | |||
3419 | const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); | |||
3420 | if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { | |||
3421 | return analyzeMemberExpr(ME); | |||
3422 | } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { | |||
3423 | if (!hasMatchingVarInit(D)) | |||
3424 | return VarInitMismatches; | |||
3425 | } | |||
3426 | return NoMismatch; | |||
3427 | } | |||
3428 | ||||
3429 | const CXXNewExpr * | |||
3430 | MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { | |||
3431 | assert(E != nullptr && "Expected a valid initializer expression")(static_cast <bool> (E != nullptr && "Expected a valid initializer expression" ) ? void (0) : __assert_fail ("E != nullptr && \"Expected a valid initializer expression\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3431, __extension__ __PRETTY_FUNCTION__ )); | |||
3432 | E = E->IgnoreParenImpCasts(); | |||
3433 | if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { | |||
3434 | if (ILE->getNumInits() == 1) | |||
3435 | E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); | |||
3436 | } | |||
3437 | ||||
3438 | return dyn_cast_or_null<const CXXNewExpr>(E); | |||
3439 | } | |||
3440 | ||||
3441 | bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( | |||
3442 | const CXXCtorInitializer *CI) { | |||
3443 | const CXXNewExpr *NE = nullptr; | |||
3444 | if (Field == CI->getMember() && | |||
3445 | (NE = getNewExprFromInitListOrExpr(CI->getInit()))) { | |||
3446 | if (NE->isArray() == IsArrayForm) | |||
3447 | return true; | |||
3448 | else | |||
3449 | NewExprs.push_back(NE); | |||
3450 | } | |||
3451 | return false; | |||
3452 | } | |||
3453 | ||||
3454 | bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( | |||
3455 | const CXXConstructorDecl *CD) { | |||
3456 | if (CD->isImplicit()) | |||
3457 | return false; | |||
3458 | const FunctionDecl *Definition = CD; | |||
3459 | if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { | |||
3460 | HasUndefinedConstructors = true; | |||
3461 | return EndOfTU; | |||
3462 | } | |||
3463 | for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { | |||
3464 | if (hasMatchingNewInCtorInit(CI)) | |||
3465 | return true; | |||
3466 | } | |||
3467 | return false; | |||
3468 | } | |||
3469 | ||||
3470 | MismatchingNewDeleteDetector::MismatchResult | |||
3471 | MismatchingNewDeleteDetector::analyzeInClassInitializer() { | |||
3472 | assert(Field != nullptr && "This should be called only for members")(static_cast <bool> (Field != nullptr && "This should be called only for members" ) ? void (0) : __assert_fail ("Field != nullptr && \"This should be called only for members\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3472, __extension__ __PRETTY_FUNCTION__ )); | |||
3473 | const Expr *InitExpr = Field->getInClassInitializer(); | |||
3474 | if (!InitExpr) | |||
3475 | return EndOfTU ? NoMismatch : AnalyzeLater; | |||
3476 | if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { | |||
3477 | if (NE->isArray() != IsArrayForm) { | |||
3478 | NewExprs.push_back(NE); | |||
3479 | return MemberInitMismatches; | |||
3480 | } | |||
3481 | } | |||
3482 | return NoMismatch; | |||
3483 | } | |||
3484 | ||||
3485 | MismatchingNewDeleteDetector::MismatchResult | |||
3486 | MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, | |||
3487 | bool DeleteWasArrayForm) { | |||
3488 | assert(Field != nullptr && "Analysis requires a valid class member.")(static_cast <bool> (Field != nullptr && "Analysis requires a valid class member." ) ? void (0) : __assert_fail ("Field != nullptr && \"Analysis requires a valid class member.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3488, __extension__ __PRETTY_FUNCTION__ )); | |||
3489 | this->Field = Field; | |||
3490 | IsArrayForm = DeleteWasArrayForm; | |||
3491 | const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); | |||
3492 | for (const auto *CD : RD->ctors()) { | |||
3493 | if (hasMatchingNewInCtor(CD)) | |||
3494 | return NoMismatch; | |||
3495 | } | |||
3496 | if (HasUndefinedConstructors) | |||
3497 | return EndOfTU ? NoMismatch : AnalyzeLater; | |||
3498 | if (!NewExprs.empty()) | |||
3499 | return MemberInitMismatches; | |||
3500 | return Field->hasInClassInitializer() ? analyzeInClassInitializer() | |||
3501 | : NoMismatch; | |||
3502 | } | |||
3503 | ||||
3504 | MismatchingNewDeleteDetector::MismatchResult | |||
3505 | MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { | |||
3506 | assert(ME != nullptr && "Expected a member expression")(static_cast <bool> (ME != nullptr && "Expected a member expression" ) ? void (0) : __assert_fail ("ME != nullptr && \"Expected a member expression\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3506, __extension__ __PRETTY_FUNCTION__ )); | |||
3507 | if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) | |||
3508 | return analyzeField(F, IsArrayForm); | |||
3509 | return NoMismatch; | |||
3510 | } | |||
3511 | ||||
3512 | bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { | |||
3513 | const CXXNewExpr *NE = nullptr; | |||
3514 | if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { | |||
3515 | if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && | |||
3516 | NE->isArray() != IsArrayForm) { | |||
3517 | NewExprs.push_back(NE); | |||
3518 | } | |||
3519 | } | |||
3520 | return NewExprs.empty(); | |||
3521 | } | |||
3522 | ||||
3523 | static void | |||
3524 | DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, | |||
3525 | const MismatchingNewDeleteDetector &Detector) { | |||
3526 | SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); | |||
3527 | FixItHint H; | |||
3528 | if (!Detector.IsArrayForm) | |||
3529 | H = FixItHint::CreateInsertion(EndOfDelete, "[]"); | |||
3530 | else { | |||
3531 | SourceLocation RSquare = Lexer::findLocationAfterToken( | |||
3532 | DeleteLoc, tok::l_square, SemaRef.getSourceManager(), | |||
3533 | SemaRef.getLangOpts(), true); | |||
3534 | if (RSquare.isValid()) | |||
3535 | H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); | |||
3536 | } | |||
3537 | SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) | |||
3538 | << Detector.IsArrayForm << H; | |||
3539 | ||||
3540 | for (const auto *NE : Detector.NewExprs) | |||
3541 | SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) | |||
3542 | << Detector.IsArrayForm; | |||
3543 | } | |||
3544 | ||||
3545 | void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { | |||
3546 | if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) | |||
3547 | return; | |||
3548 | MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); | |||
3549 | switch (Detector.analyzeDeleteExpr(DE)) { | |||
3550 | case MismatchingNewDeleteDetector::VarInitMismatches: | |||
3551 | case MismatchingNewDeleteDetector::MemberInitMismatches: { | |||
3552 | DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector); | |||
3553 | break; | |||
3554 | } | |||
3555 | case MismatchingNewDeleteDetector::AnalyzeLater: { | |||
3556 | DeleteExprs[Detector.Field].push_back( | |||
3557 | std::make_pair(DE->getBeginLoc(), DE->isArrayForm())); | |||
3558 | break; | |||
3559 | } | |||
3560 | case MismatchingNewDeleteDetector::NoMismatch: | |||
3561 | break; | |||
3562 | } | |||
3563 | } | |||
3564 | ||||
3565 | void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, | |||
3566 | bool DeleteWasArrayForm) { | |||
3567 | MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); | |||
3568 | switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { | |||
3569 | case MismatchingNewDeleteDetector::VarInitMismatches: | |||
3570 | llvm_unreachable("This analysis should have been done for class members.")::llvm::llvm_unreachable_internal("This analysis should have been done for class members." , "clang/lib/Sema/SemaExprCXX.cpp", 3570); | |||
3571 | case MismatchingNewDeleteDetector::AnalyzeLater: | |||
3572 | llvm_unreachable("Analysis cannot be postponed any point beyond end of "::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of " "translation unit.", "clang/lib/Sema/SemaExprCXX.cpp", 3573) | |||
3573 | "translation unit.")::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of " "translation unit.", "clang/lib/Sema/SemaExprCXX.cpp", 3573); | |||
3574 | case MismatchingNewDeleteDetector::MemberInitMismatches: | |||
3575 | DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); | |||
3576 | break; | |||
3577 | case MismatchingNewDeleteDetector::NoMismatch: | |||
3578 | break; | |||
3579 | } | |||
3580 | } | |||
3581 | ||||
3582 | /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: | |||
3583 | /// @code ::delete ptr; @endcode | |||
3584 | /// or | |||
3585 | /// @code delete [] ptr; @endcode | |||
3586 | ExprResult | |||
3587 | Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, | |||
3588 | bool ArrayForm, Expr *ExE) { | |||
3589 | // C++ [expr.delete]p1: | |||
3590 | // The operand shall have a pointer type, or a class type having a single | |||
3591 | // non-explicit conversion function to a pointer type. The result has type | |||
3592 | // void. | |||
3593 | // | |||
3594 | // DR599 amends "pointer type" to "pointer to object type" in both cases. | |||
3595 | ||||
3596 | ExprResult Ex = ExE; | |||
3597 | FunctionDecl *OperatorDelete = nullptr; | |||
3598 | bool ArrayFormAsWritten = ArrayForm; | |||
3599 | bool UsualArrayDeleteWantsSize = false; | |||
3600 | ||||
3601 | if (!Ex.get()->isTypeDependent()) { | |||
3602 | // Perform lvalue-to-rvalue cast, if needed. | |||
3603 | Ex = DefaultLvalueConversion(Ex.get()); | |||
3604 | if (Ex.isInvalid()) | |||
3605 | return ExprError(); | |||
3606 | ||||
3607 | QualType Type = Ex.get()->getType(); | |||
3608 | ||||
3609 | class DeleteConverter : public ContextualImplicitConverter { | |||
3610 | public: | |||
3611 | DeleteConverter() : ContextualImplicitConverter(false, true) {} | |||
3612 | ||||
3613 | bool match(QualType ConvType) override { | |||
3614 | // FIXME: If we have an operator T* and an operator void*, we must pick | |||
3615 | // the operator T*. | |||
3616 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) | |||
3617 | if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) | |||
3618 | return true; | |||
3619 | return false; | |||
3620 | } | |||
3621 | ||||
3622 | SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, | |||
3623 | QualType T) override { | |||
3624 | return S.Diag(Loc, diag::err_delete_operand) << T; | |||
3625 | } | |||
3626 | ||||
3627 | SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, | |||
3628 | QualType T) override { | |||
3629 | return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; | |||
3630 | } | |||
3631 | ||||
3632 | SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, | |||
3633 | QualType T, | |||
3634 | QualType ConvTy) override { | |||
3635 | return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; | |||
3636 | } | |||
3637 | ||||
3638 | SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, | |||
3639 | QualType ConvTy) override { | |||
3640 | return S.Diag(Conv->getLocation(), diag::note_delete_conversion) | |||
3641 | << ConvTy; | |||
3642 | } | |||
3643 | ||||
3644 | SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, | |||
3645 | QualType T) override { | |||
3646 | return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; | |||
3647 | } | |||
3648 | ||||
3649 | SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, | |||
3650 | QualType ConvTy) override { | |||
3651 | return S.Diag(Conv->getLocation(), diag::note_delete_conversion) | |||
3652 | << ConvTy; | |||
3653 | } | |||
3654 | ||||
3655 | SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, | |||
3656 | QualType T, | |||
3657 | QualType ConvTy) override { | |||
3658 | llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted" , "clang/lib/Sema/SemaExprCXX.cpp", 3658); | |||
3659 | } | |||
3660 | } Converter; | |||
3661 | ||||
3662 | Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); | |||
3663 | if (Ex.isInvalid()) | |||
3664 | return ExprError(); | |||
3665 | Type = Ex.get()->getType(); | |||
3666 | if (!Converter.match(Type)) | |||
3667 | // FIXME: PerformContextualImplicitConversion should return ExprError | |||
3668 | // itself in this case. | |||
3669 | return ExprError(); | |||
3670 | ||||
3671 | QualType Pointee = Type->castAs<PointerType>()->getPointeeType(); | |||
3672 | QualType PointeeElem = Context.getBaseElementType(Pointee); | |||
3673 | ||||
3674 | if (Pointee.getAddressSpace() != LangAS::Default && | |||
3675 | !getLangOpts().OpenCLCPlusPlus) | |||
3676 | return Diag(Ex.get()->getBeginLoc(), | |||
3677 | diag::err_address_space_qualified_delete) | |||
3678 | << Pointee.getUnqualifiedType() | |||
3679 | << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); | |||
3680 | ||||
3681 | CXXRecordDecl *PointeeRD = nullptr; | |||
3682 | if (Pointee->isVoidType() && !isSFINAEContext()) { | |||
3683 | // The C++ standard bans deleting a pointer to a non-object type, which | |||
3684 | // effectively bans deletion of "void*". However, most compilers support | |||
3685 | // this, so we treat it as a warning unless we're in a SFINAE context. | |||
3686 | Diag(StartLoc, diag::ext_delete_void_ptr_operand) | |||
3687 | << Type << Ex.get()->getSourceRange(); | |||
3688 | } else if (Pointee->isFunctionType() || Pointee->isVoidType() || | |||
3689 | Pointee->isSizelessType()) { | |||
3690 | return ExprError(Diag(StartLoc, diag::err_delete_operand) | |||
3691 | << Type << Ex.get()->getSourceRange()); | |||
3692 | } else if (!Pointee->isDependentType()) { | |||
3693 | // FIXME: This can result in errors if the definition was imported from a | |||
3694 | // module but is hidden. | |||
3695 | if (!RequireCompleteType(StartLoc, Pointee, | |||
3696 | diag::warn_delete_incomplete, Ex.get())) { | |||
3697 | if (const RecordType *RT = PointeeElem->getAs<RecordType>()) | |||
3698 | PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); | |||
3699 | } | |||
3700 | } | |||
3701 | ||||
3702 | if (Pointee->isArrayType() && !ArrayForm) { | |||
3703 | Diag(StartLoc, diag::warn_delete_array_type) | |||
3704 | << Type << Ex.get()->getSourceRange() | |||
3705 | << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); | |||
3706 | ArrayForm = true; | |||
3707 | } | |||
3708 | ||||
3709 | DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( | |||
3710 | ArrayForm ? OO_Array_Delete : OO_Delete); | |||
3711 | ||||
3712 | if (PointeeRD) { | |||
3713 | if (!UseGlobal && | |||
3714 | FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, | |||
3715 | OperatorDelete)) | |||
3716 | return ExprError(); | |||
3717 | ||||
3718 | // If we're allocating an array of records, check whether the | |||
3719 | // usual operator delete[] has a size_t parameter. | |||
3720 | if (ArrayForm) { | |||
3721 | // If the user specifically asked to use the global allocator, | |||
3722 | // we'll need to do the lookup into the class. | |||
3723 | if (UseGlobal) | |||
3724 | UsualArrayDeleteWantsSize = | |||
3725 | doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); | |||
3726 | ||||
3727 | // Otherwise, the usual operator delete[] should be the | |||
3728 | // function we just found. | |||
3729 | else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete)) | |||
3730 | UsualArrayDeleteWantsSize = | |||
3731 | UsualDeallocFnInfo(*this, | |||
3732 | DeclAccessPair::make(OperatorDelete, AS_public)) | |||
3733 | .HasSizeT; | |||
3734 | } | |||
3735 | ||||
3736 | if (!PointeeRD->hasIrrelevantDestructor()) | |||
3737 | if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { | |||
3738 | MarkFunctionReferenced(StartLoc, | |||
3739 | const_cast<CXXDestructorDecl*>(Dtor)); | |||
3740 | if (DiagnoseUseOfDecl(Dtor, StartLoc)) | |||
3741 | return ExprError(); | |||
3742 | } | |||
3743 | ||||
3744 | CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, | |||
3745 | /*IsDelete=*/true, /*CallCanBeVirtual=*/true, | |||
3746 | /*WarnOnNonAbstractTypes=*/!ArrayForm, | |||
3747 | SourceLocation()); | |||
3748 | } | |||
3749 | ||||
3750 | if (!OperatorDelete) { | |||
3751 | if (getLangOpts().OpenCLCPlusPlus) { | |||
3752 | Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; | |||
3753 | return ExprError(); | |||
3754 | } | |||
3755 | ||||
3756 | bool IsComplete = isCompleteType(StartLoc, Pointee); | |||
3757 | bool CanProvideSize = | |||
3758 | IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || | |||
3759 | Pointee.isDestructedType()); | |||
3760 | bool Overaligned = hasNewExtendedAlignment(*this, Pointee); | |||
3761 | ||||
3762 | // Look for a global declaration. | |||
3763 | OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, | |||
3764 | Overaligned, DeleteName); | |||
3765 | } | |||
3766 | ||||
3767 | MarkFunctionReferenced(StartLoc, OperatorDelete); | |||
3768 | ||||
3769 | // Check access and ambiguity of destructor if we're going to call it. | |||
3770 | // Note that this is required even for a virtual delete. | |||
3771 | bool IsVirtualDelete = false; | |||
3772 | if (PointeeRD) { | |||
3773 | if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { | |||
3774 | CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, | |||
3775 | PDiag(diag::err_access_dtor) << PointeeElem); | |||
3776 | IsVirtualDelete = Dtor->isVirtual(); | |||
3777 | } | |||
3778 | } | |||
3779 | ||||
3780 | DiagnoseUseOfDecl(OperatorDelete, StartLoc); | |||
3781 | ||||
3782 | // Convert the operand to the type of the first parameter of operator | |||
3783 | // delete. This is only necessary if we selected a destroying operator | |||
3784 | // delete that we are going to call (non-virtually); converting to void* | |||
3785 | // is trivial and left to AST consumers to handle. | |||
3786 | QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); | |||
3787 | if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { | |||
3788 | Qualifiers Qs = Pointee.getQualifiers(); | |||
3789 | if (Qs.hasCVRQualifiers()) { | |||
3790 | // Qualifiers are irrelevant to this conversion; we're only looking | |||
3791 | // for access and ambiguity. | |||
3792 | Qs.removeCVRQualifiers(); | |||
3793 | QualType Unqual = Context.getPointerType( | |||
3794 | Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs)); | |||
3795 | Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp); | |||
3796 | } | |||
3797 | Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing); | |||
3798 | if (Ex.isInvalid()) | |||
3799 | return ExprError(); | |||
3800 | } | |||
3801 | } | |||
3802 | ||||
3803 | CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( | |||
3804 | Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, | |||
3805 | UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); | |||
3806 | AnalyzeDeleteExprMismatch(Result); | |||
3807 | return Result; | |||
3808 | } | |||
3809 | ||||
3810 | static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, | |||
3811 | bool IsDelete, | |||
3812 | FunctionDecl *&Operator) { | |||
3813 | ||||
3814 | DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( | |||
3815 | IsDelete ? OO_Delete : OO_New); | |||
3816 | ||||
3817 | LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); | |||
3818 | S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); | |||
3819 | assert(!R.empty() && "implicitly declared allocation functions not found")(static_cast <bool> (!R.empty() && "implicitly declared allocation functions not found" ) ? void (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3819, __extension__ __PRETTY_FUNCTION__ )); | |||
3820 | assert(!R.isAmbiguous() && "global allocation functions are ambiguous")(static_cast <bool> (!R.isAmbiguous() && "global allocation functions are ambiguous" ) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3820, __extension__ __PRETTY_FUNCTION__ )); | |||
3821 | ||||
3822 | // We do our own custom access checks below. | |||
3823 | R.suppressDiagnostics(); | |||
3824 | ||||
3825 | SmallVector<Expr *, 8> Args(TheCall->arguments()); | |||
3826 | OverloadCandidateSet Candidates(R.getNameLoc(), | |||
3827 | OverloadCandidateSet::CSK_Normal); | |||
3828 | for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); | |||
3829 | FnOvl != FnOvlEnd; ++FnOvl) { | |||
3830 | // Even member operator new/delete are implicitly treated as | |||
3831 | // static, so don't use AddMemberCandidate. | |||
3832 | NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); | |||
3833 | ||||
3834 | if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { | |||
3835 | S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), | |||
3836 | /*ExplicitTemplateArgs=*/nullptr, Args, | |||
3837 | Candidates, | |||
3838 | /*SuppressUserConversions=*/false); | |||
3839 | continue; | |||
3840 | } | |||
3841 | ||||
3842 | FunctionDecl *Fn = cast<FunctionDecl>(D); | |||
3843 | S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, | |||
3844 | /*SuppressUserConversions=*/false); | |||
3845 | } | |||
3846 | ||||
3847 | SourceRange Range = TheCall->getSourceRange(); | |||
3848 | ||||
3849 | // Do the resolution. | |||
3850 | OverloadCandidateSet::iterator Best; | |||
3851 | switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { | |||
3852 | case OR_Success: { | |||
3853 | // Got one! | |||
3854 | FunctionDecl *FnDecl = Best->Function; | |||
3855 | assert(R.getNamingClass() == nullptr &&(static_cast <bool> (R.getNamingClass() == nullptr && "class members should not be considered") ? void (0) : __assert_fail ("R.getNamingClass() == nullptr && \"class members should not be considered\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3856, __extension__ __PRETTY_FUNCTION__ )) | |||
3856 | "class members should not be considered")(static_cast <bool> (R.getNamingClass() == nullptr && "class members should not be considered") ? void (0) : __assert_fail ("R.getNamingClass() == nullptr && \"class members should not be considered\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3856, __extension__ __PRETTY_FUNCTION__ )); | |||
3857 | ||||
3858 | if (!FnDecl->isReplaceableGlobalAllocationFunction()) { | |||
3859 | S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) | |||
3860 | << (IsDelete ? 1 : 0) << Range; | |||
3861 | S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) | |||
3862 | << R.getLookupName() << FnDecl->getSourceRange(); | |||
3863 | return true; | |||
3864 | } | |||
3865 | ||||
3866 | Operator = FnDecl; | |||
3867 | return false; | |||
3868 | } | |||
3869 | ||||
3870 | case OR_No_Viable_Function: | |||
3871 | Candidates.NoteCandidates( | |||
3872 | PartialDiagnosticAt(R.getNameLoc(), | |||
3873 | S.PDiag(diag::err_ovl_no_viable_function_in_call) | |||
3874 | << R.getLookupName() << Range), | |||
3875 | S, OCD_AllCandidates, Args); | |||
3876 | return true; | |||
3877 | ||||
3878 | case OR_Ambiguous: | |||
3879 | Candidates.NoteCandidates( | |||
3880 | PartialDiagnosticAt(R.getNameLoc(), | |||
3881 | S.PDiag(diag::err_ovl_ambiguous_call) | |||
3882 | << R.getLookupName() << Range), | |||
3883 | S, OCD_AmbiguousCandidates, Args); | |||
3884 | return true; | |||
3885 | ||||
3886 | case OR_Deleted: { | |||
3887 | Candidates.NoteCandidates( | |||
3888 | PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call) | |||
3889 | << R.getLookupName() << Range), | |||
3890 | S, OCD_AllCandidates, Args); | |||
3891 | return true; | |||
3892 | } | |||
3893 | } | |||
3894 | llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction" , "clang/lib/Sema/SemaExprCXX.cpp", 3894); | |||
3895 | } | |||
3896 | ||||
3897 | ExprResult | |||
3898 | Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, | |||
3899 | bool IsDelete) { | |||
3900 | CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); | |||
3901 | if (!getLangOpts().CPlusPlus) { | |||
3902 | Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) | |||
3903 | << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new") | |||
3904 | << "C++"; | |||
3905 | return ExprError(); | |||
3906 | } | |||
3907 | // CodeGen assumes it can find the global new and delete to call, | |||
3908 | // so ensure that they are declared. | |||
3909 | DeclareGlobalNewDelete(); | |||
3910 | ||||
3911 | FunctionDecl *OperatorNewOrDelete = nullptr; | |||
3912 | if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, | |||
3913 | OperatorNewOrDelete)) | |||
3914 | return ExprError(); | |||
3915 | assert(OperatorNewOrDelete && "should be found")(static_cast <bool> (OperatorNewOrDelete && "should be found" ) ? void (0) : __assert_fail ("OperatorNewOrDelete && \"should be found\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3915, __extension__ __PRETTY_FUNCTION__ )); | |||
3916 | ||||
3917 | DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc()); | |||
3918 | MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete); | |||
3919 | ||||
3920 | TheCall->setType(OperatorNewOrDelete->getReturnType()); | |||
3921 | for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { | |||
3922 | QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); | |||
3923 | InitializedEntity Entity = | |||
3924 | InitializedEntity::InitializeParameter(Context, ParamTy, false); | |||
3925 | ExprResult Arg = PerformCopyInitialization( | |||
3926 | Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i)); | |||
3927 | if (Arg.isInvalid()) | |||
3928 | return ExprError(); | |||
3929 | TheCall->setArg(i, Arg.get()); | |||
3930 | } | |||
3931 | auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee()); | |||
3932 | assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&(static_cast <bool> (Callee && Callee->getCastKind () == CK_BuiltinFnToFnPtr && "Callee expected to be implicit cast to a builtin function pointer" ) ? void (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3933, __extension__ __PRETTY_FUNCTION__ )) | |||
3933 | "Callee expected to be implicit cast to a builtin function pointer")(static_cast <bool> (Callee && Callee->getCastKind () == CK_BuiltinFnToFnPtr && "Callee expected to be implicit cast to a builtin function pointer" ) ? void (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\"" , "clang/lib/Sema/SemaExprCXX.cpp", 3933, __extension__ __PRETTY_FUNCTION__ )); | |||
3934 | Callee->setType(OperatorNewOrDelete->getType()); | |||
3935 | ||||
3936 | return TheCallResult; | |||
3937 | } | |||
3938 | ||||
3939 | void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, | |||
3940 | bool IsDelete, bool CallCanBeVirtual, | |||
3941 | bool WarnOnNonAbstractTypes, | |||
3942 | SourceLocation DtorLoc) { | |||
3943 | if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) | |||
3944 | return; | |||
3945 | ||||
3946 | // C++ [expr.delete]p3: | |||
3947 | // In the first alternative (delete object), if the static type of the | |||
3948 | // object to be deleted is different from its dynamic type, the static | |||
3949 | // type shall be a base class of the dynamic type of the object to be | |||
3950 | // deleted and the static type shall have a virtual destructor or the | |||
3951 | // behavior is undefined. | |||
3952 | // | |||
3953 | const CXXRecordDecl *PointeeRD = dtor->getParent(); | |||
3954 | // Note: a final class cannot be derived from, no issue there | |||
3955 | if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) | |||
3956 | return; | |||
3957 | ||||
3958 | // If the superclass is in a system header, there's nothing that can be done. | |||
3959 | // The `delete` (where we emit the warning) can be in a system header, | |||
3960 | // what matters for this warning is where the deleted type is defined. | |||
3961 | if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) | |||
3962 | return; | |||
3963 | ||||
3964 | QualType ClassType = dtor->getThisType()->getPointeeType(); | |||
3965 | if (PointeeRD->isAbstract()) { | |||
3966 | // If the class is abstract, we warn by default, because we're | |||
3967 | // sure the code has undefined behavior. | |||
3968 | Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) | |||
3969 | << ClassType; | |||
3970 | } else if (WarnOnNonAbstractTypes) { | |||
3971 | // Otherwise, if this is not an array delete, it's a bit suspect, | |||
3972 | // but not necessarily wrong. | |||
3973 | Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) | |||
3974 | << ClassType; | |||
3975 | } | |||
3976 | if (!IsDelete) { | |||
3977 | std::string TypeStr; | |||
3978 | ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); | |||
3979 | Diag(DtorLoc, diag::note_delete_non_virtual) | |||
3980 | << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); | |||
3981 | } | |||
3982 | } | |||
3983 | ||||
3984 | Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, | |||
3985 | SourceLocation StmtLoc, | |||
3986 | ConditionKind CK) { | |||
3987 | ExprResult E = | |||
3988 | CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); | |||
3989 | if (E.isInvalid()) | |||
3990 | return ConditionError(); | |||
3991 | return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc), | |||
3992 | CK == ConditionKind::ConstexprIf); | |||
3993 | } | |||
3994 | ||||
3995 | /// Check the use of the given variable as a C++ condition in an if, | |||
3996 | /// while, do-while, or switch statement. | |||
3997 | ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, | |||
3998 | SourceLocation StmtLoc, | |||
3999 | ConditionKind CK) { | |||
4000 | if (ConditionVar->isInvalidDecl()) | |||
4001 | return ExprError(); | |||
4002 | ||||
4003 | QualType T = ConditionVar->getType(); | |||
4004 | ||||
4005 | // C++ [stmt.select]p2: | |||
4006 | // The declarator shall not specify a function or an array. | |||
4007 | if (T->isFunctionType()) | |||
4008 | return ExprError(Diag(ConditionVar->getLocation(), | |||
4009 | diag::err_invalid_use_of_function_type) | |||
4010 | << ConditionVar->getSourceRange()); | |||
4011 | else if (T->isArrayType()) | |||
4012 | return ExprError(Diag(ConditionVar->getLocation(), | |||
4013 | diag::err_invalid_use_of_array_type) | |||
4014 | << ConditionVar->getSourceRange()); | |||
4015 | ||||
4016 | ExprResult Condition = BuildDeclRefExpr( | |||
4017 | ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, | |||
4018 | ConditionVar->getLocation()); | |||
4019 | ||||
4020 | switch (CK) { | |||
4021 | case ConditionKind::Boolean: | |||
4022 | return CheckBooleanCondition(StmtLoc, Condition.get()); | |||
4023 | ||||
4024 | case ConditionKind::ConstexprIf: | |||
4025 | return CheckBooleanCondition(StmtLoc, Condition.get(), true); | |||
4026 | ||||
4027 | case ConditionKind::Switch: | |||
4028 | return CheckSwitchCondition(StmtLoc, Condition.get()); | |||
4029 | } | |||
4030 | ||||
4031 | llvm_unreachable("unexpected condition kind")::llvm::llvm_unreachable_internal("unexpected condition kind" , "clang/lib/Sema/SemaExprCXX.cpp", 4031); | |||
4032 | } | |||
4033 | ||||
4034 | /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. | |||
4035 | ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { | |||
4036 | // C++11 6.4p4: | |||
4037 | // The value of a condition that is an initialized declaration in a statement | |||
4038 | // other than a switch statement is the value of the declared variable | |||
4039 | // implicitly converted to type bool. If that conversion is ill-formed, the | |||
4040 | // program is ill-formed. | |||
4041 | // The value of a condition that is an expression is the value of the | |||
4042 | // expression, implicitly converted to bool. | |||
4043 | // | |||
4044 | // C++2b 8.5.2p2 | |||
4045 | // If the if statement is of the form if constexpr, the value of the condition | |||
4046 | // is contextually converted to bool and the converted expression shall be | |||
4047 | // a constant expression. | |||
4048 | // | |||
4049 | ||||
4050 | ExprResult E = PerformContextuallyConvertToBool(CondExpr); | |||
4051 | if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent()) | |||
4052 | return E; | |||
4053 | ||||
4054 | // FIXME: Return this value to the caller so they don't need to recompute it. | |||
4055 | llvm::APSInt Cond; | |||
4056 | E = VerifyIntegerConstantExpression( | |||
4057 | E.get(), &Cond, | |||
4058 | diag::err_constexpr_if_condition_expression_is_not_constant); | |||
4059 | return E; | |||
4060 | } | |||
4061 | ||||
4062 | /// Helper function to determine whether this is the (deprecated) C++ | |||
4063 | /// conversion from a string literal to a pointer to non-const char or | |||
4064 | /// non-const wchar_t (for narrow and wide string literals, | |||
4065 | /// respectively). | |||
4066 | bool | |||
4067 | Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { | |||
4068 | // Look inside the implicit cast, if it exists. | |||
4069 | if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) | |||
4070 | From = Cast->getSubExpr(); | |||
4071 | ||||
4072 | // A string literal (2.13.4) that is not a wide string literal can | |||
4073 | // be converted to an rvalue of type "pointer to char"; a wide | |||
4074 | // string literal can be converted to an rvalue of type "pointer | |||
4075 | // to wchar_t" (C++ 4.2p2). | |||
4076 | if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) | |||
4077 | if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) | |||
4078 | if (const BuiltinType *ToPointeeType | |||
4079 | = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { | |||
4080 | // This conversion is considered only when there is an | |||
4081 | // explicit appropriate pointer target type (C++ 4.2p2). | |||
4082 | if (!ToPtrType->getPointeeType().hasQualifiers()) { | |||
4083 | switch (StrLit->getKind()) { | |||
4084 | case StringLiteral::UTF8: | |||
4085 | case StringLiteral::UTF16: | |||
4086 | case StringLiteral::UTF32: | |||
4087 | // We don't allow UTF literals to be implicitly converted | |||
4088 | break; | |||
4089 | case StringLiteral::Ordinary: | |||
4090 | return (ToPointeeType->getKind() == BuiltinType::Char_U || | |||
4091 | ToPointeeType->getKind() == BuiltinType::Char_S); | |||
4092 | case StringLiteral::Wide: | |||
4093 | return Context.typesAreCompatible(Context.getWideCharType(), | |||
4094 | QualType(ToPointeeType, 0)); | |||
4095 | } | |||
4096 | } | |||
4097 | } | |||
4098 | ||||
4099 | return false; | |||
4100 | } | |||
4101 | ||||
4102 | static ExprResult BuildCXXCastArgument(Sema &S, | |||
4103 | SourceLocation CastLoc, | |||
4104 | QualType Ty, | |||
4105 | CastKind Kind, | |||
4106 | CXXMethodDecl *Method, | |||
4107 | DeclAccessPair FoundDecl, | |||
4108 | bool HadMultipleCandidates, | |||
4109 | Expr *From) { | |||
4110 | switch (Kind) { | |||
4111 | default: llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "clang/lib/Sema/SemaExprCXX.cpp" , 4111); | |||
4112 | case CK_ConstructorConversion: { | |||
4113 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); | |||
4114 | SmallVector<Expr*, 8> ConstructorArgs; | |||
4115 | ||||
4116 | if (S.RequireNonAbstractType(CastLoc, Ty, | |||
4117 | diag::err_allocation_of_abstract_type)) | |||
4118 | return ExprError(); | |||
4119 | ||||
4120 | if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc, | |||
4121 | ConstructorArgs)) | |||
4122 | return ExprError(); | |||
4123 | ||||
4124 | S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, | |||
4125 | InitializedEntity::InitializeTemporary(Ty)); | |||
4126 | if (S.DiagnoseUseOfDecl(Method, CastLoc)) | |||
4127 | return ExprError(); | |||
4128 | ||||
4129 | ExprResult Result = S.BuildCXXConstructExpr( | |||
4130 | CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), | |||
4131 | ConstructorArgs, HadMultipleCandidates, | |||
4132 | /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, | |||
4133 | CXXConstructExpr::CK_Complete, SourceRange()); | |||
4134 | if (Result.isInvalid()) | |||
4135 | return ExprError(); | |||
4136 | ||||
4137 | return S.MaybeBindToTemporary(Result.getAs<Expr>()); | |||
4138 | } | |||
4139 | ||||
4140 | case CK_UserDefinedConversion: { | |||
4141 | assert(!From->getType()->isPointerType() && "Arg can't have pointer type!")(static_cast <bool> (!From->getType()->isPointerType () && "Arg can't have pointer type!") ? void (0) : __assert_fail ("!From->getType()->isPointerType() && \"Arg can't have pointer type!\"" , "clang/lib/Sema/SemaExprCXX.cpp", 4141, __extension__ __PRETTY_FUNCTION__ )); | |||
4142 | ||||
4143 | S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); | |||
4144 | if (S.DiagnoseUseOfDecl(Method, CastLoc)) | |||
4145 | return ExprError(); | |||
4146 | ||||
4147 | // Create an implicit call expr that calls it. | |||
4148 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); | |||
4149 | ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, | |||
4150 | HadMultipleCandidates); | |||
4151 | if (Result.isInvalid()) | |||
4152 | return ExprError(); | |||
4153 | // Record usage of conversion in an implicit cast. | |||
4154 | Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), | |||
4155 | CK_UserDefinedConversion, Result.get(), | |||
4156 | nullptr, Result.get()->getValueKind(), | |||
4157 | S.CurFPFeatureOverrides()); | |||
4158 | ||||
4159 | return S.MaybeBindToTemporary(Result.get()); | |||
4160 | } | |||
4161 | } | |||
4162 | } | |||
4163 | ||||
4164 | /// PerformImplicitConversion - Perform an implicit conversion of the | |||
4165 | /// expression From to the type ToType using the pre-computed implicit | |||
4166 | /// conversion sequence ICS. Returns the converted | |||
4167 | /// expression. Action is the kind of conversion we're performing, | |||
4168 | /// used in the error message. | |||
4169 | ExprResult | |||
4170 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, | |||
4171 | const ImplicitConversionSequence &ICS, | |||
4172 | AssignmentAction Action, | |||
4173 | CheckedConversionKind CCK) { | |||
4174 | // C++ [over.match.oper]p7: [...] operands of class type are converted [...] | |||
4175 | if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType()) | |||
4176 | return From; | |||
4177 | ||||
4178 | switch (ICS.getKind()) { | |||
4179 | case ImplicitConversionSequence::StandardConversion: { | |||
4180 | ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, | |||
4181 | Action, CCK); | |||
4182 | if (Res.isInvalid()) | |||
4183 | return ExprError(); | |||
4184 | From = Res.get(); | |||
4185 | break; | |||
4186 | } | |||
4187 | ||||
4188 | case ImplicitConversionSequence::UserDefinedConversion: { | |||
4189 | ||||
4190 | FunctionDecl *FD = ICS.UserDefined.ConversionFunction; | |||
4191 | CastKind CastKind; | |||
4192 | QualType BeforeToType; | |||
4193 | assert(FD && "no conversion function for user-defined conversion seq")(static_cast <bool> (FD && "no conversion function for user-defined conversion seq" ) ? void (0) : __assert_fail ("FD && \"no conversion function for user-defined conversion seq\"" , "clang/lib/Sema/SemaExprCXX.cpp", 4193, __extension__ __PRETTY_FUNCTION__ )); | |||
4194 | if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { | |||
4195 | CastKind = CK_UserDefinedConversion; | |||
4196 | ||||
4197 | // If the user-defined conversion is specified by a conversion function, | |||
4198 | // the initial standard conversion sequence converts the source type to | |||
4199 | // the implicit object parameter of the conversion function. | |||
4200 | BeforeToType = Context.getTagDeclType(Conv->getParent()); | |||
4201 | } else { | |||
4202 | const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); | |||
4203 | CastKind = CK_ConstructorConversion; | |||
4204 | // Do no conversion if dealing with ... for the first conversion. | |||
4205 | if (!ICS.UserDefined.EllipsisConversion) { | |||
4206 | // If the user-defined conversion is specified by a constructor, the | |||
4207 | // initial standard conversion sequence converts the source type to | |||
4208 | // the type required by the argument of the constructor | |||
4209 | BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); | |||
4210 | } | |||
4211 | } | |||
4212 | // Watch out for ellipsis conversion. | |||
4213 | if (!ICS.UserDefined.EllipsisConversion) { | |||
4214 | ExprResult Res = | |||
4215 | PerformImplicitConversion(From, BeforeToType, | |||
4216 | ICS.UserDefined.Before, AA_Converting, | |||
4217 | CCK); | |||
4218 | if (Res.isInvalid()) | |||
4219 | return ExprError(); | |||
4220 | From = Res.get(); | |||
4221 | } | |||
4222 | ||||
4223 | ExprResult CastArg = BuildCXXCastArgument( | |||
4224 | *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, | |||
4225 | cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction, | |||
4226 | ICS.UserDefined.HadMultipleCandidates, From); | |||
4227 | ||||
4228 | if (CastArg.isInvalid()) | |||
4229 | return ExprError(); | |||
4230 | ||||
4231 | From = CastArg.get(); | |||
4232 | ||||
4233 | // C++ [over.match.oper]p7: | |||
4234 | // [...] the second standard conversion sequence of a user-defined | |||
4235 | // conversion sequence is not applied. | |||
4236 | if (CCK == CCK_ForBuiltinOverloadedOp) | |||
4237 | return From; | |||
4238 | ||||
4239 | return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, | |||
4240 | AA_Converting, CCK); | |||
4241 | } | |||
4242 | ||||
4243 | case ImplicitConversionSequence::AmbiguousConversion: | |||
4244 | ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), | |||
4245 | PDiag(diag::err_typecheck_ambiguous_condition) | |||
4246 | << From->getSourceRange()); | |||
4247 | return ExprError(); | |||
4248 | ||||
4249 | case ImplicitConversionSequence::EllipsisConversion: | |||
4250 | case ImplicitConversionSequence::StaticObjectArgumentConversion: | |||
4251 | llvm_unreachable("bad conversion")::llvm::llvm_unreachable_internal("bad conversion", "clang/lib/Sema/SemaExprCXX.cpp" , 4251); | |||
4252 | ||||
4253 | case ImplicitConversionSequence::BadConversion: | |||
4254 | Sema::AssignConvertType ConvTy = | |||
4255 | CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType()); | |||
4256 | bool Diagnosed = DiagnoseAssignmentResult( | |||
4257 | ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(), | |||
4258 | ToType, From->getType(), From, Action); | |||
4259 | assert(Diagnosed && "failed to diagnose bad conversion")(static_cast <bool> (Diagnosed && "failed to diagnose bad conversion" ) ? void (0) : __assert_fail ("Diagnosed && \"failed to diagnose bad conversion\"" , "clang/lib/Sema/SemaExprCXX.cpp", 4259, __extension__ __PRETTY_FUNCTION__ )); (void)Diagnosed; | |||
4260 | return ExprError(); | |||
4261 | } | |||
4262 | ||||
4263 | // Everything went well. | |||
4264 | return From; | |||
4265 | } | |||
4266 | ||||
4267 | /// PerformImplicitConversion - Perform an implicit conversion of the | |||
4268 | /// expression From to the type ToType by following the standard | |||
4269 | /// conversion sequence SCS. Returns the converted | |||
4270 | /// expression. Flavor is the context in which we're performing this | |||
4271 | /// conversion, for use in error messages. | |||
4272 | ExprResult | |||
4273 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, | |||
4274 | const StandardConversionSequence& SCS, | |||
4275 | AssignmentAction Action, | |||
4276 | CheckedConversionKind CCK) { | |||
4277 | bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); | |||
4278 | ||||
4279 | // Overall FIXME: we are recomputing too many types here and doing far too | |||
4280 | // much extra work. What this means is that we need to keep track of more | |||
4281 | // information that is computed when we try the implicit conversion initially, | |||
4282 | // so that we don't need to recompute anything here. | |||
4283 | QualType FromType = From->getType(); | |||
4284 | ||||
4285 | if (SCS.CopyConstructor) { | |||
4286 | // FIXME: When can ToType be a reference type? | |||
4287 | assert(!ToType->isReferenceType())(static_cast <bool> (!ToType->isReferenceType()) ? void (0) : __assert_fail ("!ToType->isReferenceType()", "clang/lib/Sema/SemaExprCXX.cpp" , 4287, __extension__ __PRETTY_FUNCTION__)); | |||
4288 | if (SCS.Second == ICK_Derived_To_Base) { | |||
4289 | SmallVector<Expr*, 8> ConstructorArgs; | |||
4290 | if (CompleteConstructorCall( | |||
4291 | cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From, | |||
4292 | /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs)) | |||
4293 | return ExprError(); | |||
4294 | return BuildCXXConstructExpr( | |||
4295 | /*FIXME:ConstructLoc*/ SourceLocation(), ToType, | |||
4296 | SCS.FoundCopyConstructor, SCS.CopyConstructor, | |||
4297 | ConstructorArgs, /*HadMultipleCandidates*/ false, | |||
4298 | /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, | |||
4299 | CXXConstructExpr::CK_Complete, SourceRange()); | |||
4300 | } | |||
4301 | return BuildCXXConstructExpr( | |||
4302 | /*FIXME:ConstructLoc*/ SourceLocation(), ToType, | |||
4303 | SCS.FoundCopyConstructor, SCS.CopyConstructor, | |||
4304 | From, /*HadMultipleCandidates*/ false, | |||
4305 | /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, | |||
4306 | CXXConstructExpr::CK_Complete, SourceRange()); | |||
4307 | } | |||
4308 | ||||
4309 | // Resolve overloaded function references. | |||
4310 | if (Context.hasSameType(FromType, Context.OverloadTy)) { | |||
4311 | DeclAccessPair Found; | |||
4312 | FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, | |||
4313 | true, Found); | |||
4314 | if (!Fn) | |||
4315 | return ExprError(); | |||
4316 | ||||
4317 | if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) | |||
4318 | return ExprError(); | |||
4319 | ||||
4320 | From = FixOverloadedFunctionReference(From, Found, Fn); | |||
4321 | ||||
4322 | // We might get back another placeholder expression if we resolved to a | |||
4323 | // builtin. | |||
4324 | ExprResult Checked = CheckPlaceholderExpr(From); | |||
4325 | if (Checked.isInvalid()) | |||
4326 | return ExprError(); | |||
4327 | ||||
4328 | From = Checked.get(); | |||
4329 | FromType = From->getType(); | |||
4330 | } | |||
4331 | ||||
4332 | // If we're converting to an atomic type, first convert to the corresponding | |||
4333 | // non-atomic type. | |||
4334 | QualType ToAtomicType; | |||
4335 | if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { | |||
4336 | ToAtomicType = ToType; | |||
4337 | ToType = ToAtomic->getValueType(); | |||
4338 | } | |||
4339 | ||||
4340 | QualType InitialFromType = FromType; | |||
4341 | // Perform the first implicit conversion. | |||
4342 | switch (SCS.First) { | |||
4343 | case ICK_Identity: | |||
4344 | if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { | |||
4345 | FromType = FromAtomic->getValueType().getUnqualifiedType(); | |||
4346 | From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, | |||
4347 | From, /*BasePath=*/nullptr, VK_PRValue, | |||
4348 | FPOptionsOverride()); | |||
4349 | } | |||
4350 | break; | |||
4351 | ||||
4352 | case ICK_Lvalue_To_Rvalue: { | |||
4353 | assert(From->getObjectKind() != OK_ObjCProperty)(static_cast <bool> (From->getObjectKind() != OK_ObjCProperty ) ? void (0) : __assert_fail ("From->getObjectKind() != OK_ObjCProperty" , "clang/lib/Sema/SemaExprCXX.cpp", 4353, __extension__ __PRETTY_FUNCTION__ )); | |||
4354 | ExprResult FromRes = DefaultLvalueConversion(From); | |||
4355 | if (FromRes.isInvalid()) | |||
4356 | return ExprError(); | |||
4357 | ||||
4358 | From = FromRes.get(); | |||
4359 | FromType = From->getType(); | |||
4360 | break; | |||
4361 | } | |||
4362 | ||||
4363 | case ICK_Array_To_Pointer: | |||
4364 | FromType = Context.getArrayDecayedType(FromType); | |||
4365 | From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue, | |||
4366 | /*BasePath=*/nullptr, CCK) | |||
4367 | .get(); | |||
4368 | break; | |||
4369 | ||||
4370 | case ICK_Function_To_Pointer: | |||
4371 | FromType = Context.getPointerType(FromType); | |||
4372 | From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, | |||
4373 | VK_PRValue, /*BasePath=*/nullptr, CCK) | |||
4374 | .get(); | |||
4375 | break; | |||
4376 | ||||
4377 | default: | |||
4378 | llvm_unreachable("Improper first standard conversion")::llvm::llvm_unreachable_internal("Improper first standard conversion" , "clang/lib/Sema/SemaExprCXX.cpp", 4378); | |||
4379 | } | |||
4380 | ||||
4381 | // Perform the second implicit conversion | |||
4382 | switch (SCS.Second) { | |||
4383 | case ICK_Identity: | |||
4384 | // C++ [except.spec]p5: | |||
4385 | // [For] assignment to and initialization of pointers to functions, | |||
4386 | // pointers to member functions, and references to functions: the | |||
4387 | // target entity shall allow at least the exceptions allowed by the | |||
4388 | // source value in the assignment or initialization. | |||
4389 | switch (Action) { | |||
4390 | case AA_Assigning: | |||
4391 | case AA_Initializing: | |||
4392 | // Note, function argument passing and returning are initialization. | |||
4393 | case AA_Passing: | |||
4394 | case AA_Returning: | |||
4395 | case AA_Sending: | |||
4396 | case AA_Passing_CFAudited: | |||
4397 | if (CheckExceptionSpecCompatibility(From, ToType)) | |||
4398 | return ExprError(); | |||
4399 | break; | |||
4400 | ||||
4401 | case AA_Casting: | |||
4402 | case AA_Converting: | |||
4403 | // Casts and implicit conversions are not initialization, so are not | |||
4404 | // checked for exception specification mismatches. | |||
4405 | break; | |||
4406 | } | |||
4407 | // Nothing else to do. | |||
4408 | break; | |||
4409 | ||||
4410 | case ICK_Integral_Promotion: | |||
4411 | case ICK_Integral_Conversion: | |||
4412 | if (ToType->isBooleanType()) { | |||
4413 | assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&(static_cast <bool> (FromType->castAs<EnumType> ()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && "only enums with fixed underlying type can promote to bool" ) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\"" , "clang/lib/Sema/SemaExprCXX.cpp", 4415, __extension__ __PRETTY_FUNCTION__ )) | |||
4414 | SCS.Second == ICK_Integral_Promotion &&(static_cast <bool> (FromType->castAs<EnumType> ()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && "only enums with fixed underlying type can promote to bool" ) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\"" , "clang/lib/Sema/SemaExprCXX.cpp", 4415, __extension__ __PRETTY_FUNCTION__ )) | |||
4415 | "only enums with fixed underlying type can promote to bool")(static_cast <bool> (FromType->castAs<EnumType> ()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && "only enums with fixed underlying type can promote to bool" ) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\"" , "clang/lib/Sema/SemaExprCXX.cpp", 4415, __extension__ __PRETTY_FUNCTION__ )); | |||
4416 | From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue, | |||
4417 | /*BasePath=*/nullptr, CCK) | |||
4418 | .get(); | |||
4419 | } else { | |||
4420 | From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue, | |||
4421 | /*BasePath=*/nullptr, CCK) | |||
4422 | .get(); | |||
4423 | } | |||
4424 | break; | |||
4425 | ||||
4426 | case ICK_Floating_Promotion: | |||
4427 | case ICK_Floating_Conversion: | |||
4428 | From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue, | |||
4429 | /*BasePath=*/nullptr, CCK) | |||
4430 | .get(); | |||
4431 | break; | |||
4432 | ||||
4433 | case ICK_Complex_Promotion: | |||
4434 | case ICK_Complex_Conversion: { | |||
4435 | QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType(); | |||
4436 | QualType ToEl = ToType->castAs<ComplexType>()->getElementType(); | |||
4437 | CastKind CK; | |||
4438 | if (FromEl->isRealFloatingType()) { | |||
4439 | if (ToEl->isRealFloatingType()) | |||
4440 | CK = CK_FloatingComplexCast; | |||
4441 | else | |||
4442 | CK = CK_FloatingComplexToIntegralComplex; | |||
4443 | } else if (ToEl->isRealFloatingType()) { | |||
4444 | CK = CK_IntegralComplexToFloatingComplex; | |||
4445 | } else { | |||
4446 | CK = CK_IntegralComplexCast; | |||
4447 | } | |||
4448 | From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr, | |||
4449 | CCK) | |||
4450 | .get(); | |||
4451 | break; | |||
4452 | } | |||
4453 | ||||
4454 | case ICK_Floating_Integral: | |||
4455 | if (ToType->isRealFloatingType()) | |||
4456 | From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue, | |||
4457 | /*BasePath=*/nullptr, CCK) | |||
4458 | .get(); | |||
4459 | else | |||
4460 | From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue, | |||
4461 | /*BasePath=*/nullptr, CCK) | |||
4462 | .get(); | |||
4463 | break; | |||
4464 | ||||
4465 | case ICK_Compatible_Conversion: | |||
4466 | From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(), | |||
4467 | /*BasePath=*/nullptr, CCK).get(); | |||
4468 | break; | |||
4469 | ||||
4470 | case ICK_Writeback_Conversion: | |||
4471 | case ICK_Pointer_Conversion: { | |||
4472 | if (SCS.IncompatibleObjC && Action != AA_Casting) { | |||
4473 | // Diagnose incompatible Objective-C conversions | |||
4474 | if (Action == AA_Initializing || Action == AA_Assigning) | |||
4475 | Diag(From->getBeginLoc(), | |||
4476 | diag::ext_typecheck_convert_incompatible_pointer) | |||
4477 | << ToType << From->getType() << Action << From->getSourceRange() | |||
4478 | << 0; | |||
4479 | else | |||
4480 | Diag(From->getBeginLoc(), | |||
4481 | diag::ext_typecheck_convert_incompatible_pointer) | |||
4482 | << From->getType() << ToType << Action << From->getSourceRange() | |||
4483 | << 0; | |||
4484 | ||||
4485 | if (From->getType()->isObjCObjectPointerType() && | |||
4486 | ToType->isObjCObjectPointerType()) | |||
4487 | EmitRelatedResultTypeNote(From); | |||
4488 | } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
4489 | !CheckObjCARCUnavailableWeakConversion(ToType, | |||
4490 | From->getType())) { | |||
4491 | if (Action == AA_Initializing) | |||
4492 | Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); | |||
4493 | else | |||
4494 | Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) | |||
4495 | << (Action == AA_Casting) << From->getType() << ToType | |||
4496 | << From->getSourceRange(); | |||
4497 | } | |||
4498 | ||||
4499 | // Defer address space conversion to the third conversion. | |||
4500 | QualType FromPteeType = From->getType()->getPointeeType(); | |||
4501 | QualType ToPteeType = ToType->getPointeeType(); | |||
4502 | QualType NewToType = ToType; | |||
4503 | if (!FromPteeType.isNull() && !ToPteeType.isNull() && | |||
4504 | FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) { | |||
4505 | NewToType = Context.removeAddrSpaceQualType(ToPteeType); | |||
4506 | NewToType = Context.getAddrSpaceQualType(NewToType, | |||
4507 | FromPteeType.getAddressSpace()); | |||
4508 | if (ToType->isObjCObjectPointerType()) | |||
4509 | NewToType = Context.getObjCObjectPointerType(NewToType); | |||
4510 | else if (ToType->isBlockPointerType()) | |||
4511 | NewToType = Context.getBlockPointerType(NewToType); | |||
4512 | else | |||
4513 | NewToType = Context.getPointerType(NewToType); | |||
4514 | } | |||
4515 | ||||
4516 | CastKind Kind; | |||
4517 | CXXCastPath BasePath; | |||
4518 | if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle)) | |||
4519 | return ExprError(); | |||
4520 | ||||
4521 | // Make sure we extend blocks if necessary. | |||
4522 | // FIXME: doing this here is really ugly. | |||
4523 | if (Kind == CK_BlockPointerToObjCPointerCast) { | |||
4524 | ExprResult E = From; | |||
4525 | (void) PrepareCastToObjCObjectPointer(E); | |||
4526 | From = E.get(); | |||
4527 | } | |||
4528 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) | |||
4529 | CheckObjCConversion(SourceRange(), NewToType, From, CCK); | |||
4530 | From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK) | |||
4531 | .get(); | |||
4532 | break; | |||
4533 | } | |||
4534 | ||||
4535 | case ICK_Pointer_Member: { | |||
4536 | CastKind Kind; | |||
4537 | CXXCastPath BasePath; | |||
4538 | if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) | |||
4539 | return ExprError(); | |||
4540 | if (CheckExceptionSpecCompatibility(From, ToType)) | |||
4541 | return ExprError(); | |||
4542 | ||||
4543 | // We may not have been able to figure out what this member pointer resolved | |||
4544 | // to up until this exact point. Attempt to lock-in it's inheritance model. | |||
4545 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
4546 | (void)isCompleteType(From->getExprLoc(), From->getType()); | |||
4547 | (void)isCompleteType(From->getExprLoc(), ToType); | |||
4548 | } | |||
4549 | ||||
4550 | From = | |||
4551 | ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get(); | |||
4552 | break; | |||
4553 | } | |||
4554 | ||||
4555 | case ICK_Boolean_Conversion: | |||
4556 | // Perform half-to-boolean conversion via float. | |||
4557 | if (From->getType()->isHalfType()) { | |||
4558 | From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); | |||
4559 | FromType = Context.FloatTy; | |||
4560 | } | |||
4561 | ||||
4562 | From = ImpCastExprToType(From, Context.BoolTy, | |||
4563 | ScalarTypeToBooleanCastKind(FromType), VK_PRValue, | |||
4564 | /*BasePath=*/nullptr, CCK) | |||
4565 | .get(); | |||
4566 | break; | |||
4567 | ||||
4568 | case ICK_Derived_To_Base: { | |||
4569 | CXXCastPath BasePath; | |||
4570 | if (CheckDerivedToBaseConversion( | |||
4571 | From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), | |||
4572 | From->getSourceRange(), &BasePath, CStyle)) | |||
4573 | return ExprError(); | |||
4574 | ||||
4575 | From = ImpCastExprToType(From, ToType.getNonReferenceType(), | |||
4576 | CK_DerivedToBase, From->getValueKind(), | |||
4577 | &BasePath, CCK).get(); | |||
4578 | break; | |||
4579 | } | |||
4580 | ||||
4581 | case ICK_Vector_Conversion: | |||
4582 | From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue, | |||
4583 | /*BasePath=*/nullptr, CCK) | |||
4584 | .get(); | |||
4585 | break; | |||
4586 | ||||
4587 | case ICK_SVE_Vector_Conversion: | |||
4588 | From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue, | |||
4589 | /*BasePath=*/nullptr, CCK) | |||
4590 | .get(); | |||
4591 | break; | |||
4592 | ||||
4593 | case ICK_Vector_Splat: { | |||
4594 | // Vector splat from any arithmetic type to a vector. | |||
4595 | Expr *Elem = prepareVectorSplat(ToType, From).get(); | |||
4596 | From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue, | |||
4597 | /*BasePath=*/nullptr, CCK) | |||
4598 | .get(); | |||
4599 | break; | |||
4600 | } | |||
4601 | ||||
4602 | case ICK_Complex_Real: | |||
4603 | // Case 1. x -> _Complex y | |||
4604 | if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { | |||
4605 | QualType ElType = ToComplex->getElementType(); | |||
4606 | bool isFloatingComplex = ElType->isRealFloatingType(); | |||
4607 | ||||
4608 | // x -> y | |||
4609 | if (Context.hasSameUnqualifiedType(ElType, From->getType())) { | |||
4610 | // do nothing | |||
4611 | } else if (From->getType()->isRealFloatingType()) { | |||
4612 | From = ImpCastExprToType(From, ElType, | |||
4613 | isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); | |||
4614 | } else { | |||
4615 | assert(From->getType()->isIntegerType())(static_cast <bool> (From->getType()->isIntegerType ()) ? void (0) : __assert_fail ("From->getType()->isIntegerType()" , "clang/lib/Sema/SemaExprCXX.cpp", 4615, __extension__ __PRETTY_FUNCTION__ )); | |||
4616 | From = ImpCastExprToType(From, ElType, | |||
4617 | isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); | |||
4618 | } | |||
4619 | // y -> _Complex y | |||
4620 | From = ImpCastExprToType(From, ToType, | |||
4621 | isFloatingComplex ? CK_FloatingRealToComplex | |||
4622 | : CK_IntegralRealToComplex).get(); | |||
4623 | ||||
4624 | // Case 2. _Complex x -> y | |||
4625 | } else { | |||
4626 | auto *FromComplex = From->getType()->castAs<ComplexType>(); | |||
4627 | QualType ElType = FromComplex->getElementType(); | |||
4628 | bool isFloatingComplex = ElType->isRealFloatingType(); | |||
4629 | ||||
4630 | // _Complex x -> x | |||
4631 | From = ImpCastExprToType(From, ElType, | |||
4632 | isFloatingComplex ? CK_FloatingComplexToReal | |||
4633 | : CK_IntegralComplexToReal, | |||
4634 | VK_PRValue, /*BasePath=*/nullptr, CCK) | |||
4635 | .get(); | |||
4636 | ||||
4637 | // x -> y | |||
4638 | if (Context.hasSameUnqualifiedType(ElType, ToType)) { | |||
4639 | // do nothing | |||
4640 | } else if (ToType->isRealFloatingType()) { | |||
4641 | From = ImpCastExprToType(From, ToType, | |||
4642 | isFloatingComplex ? CK_FloatingCast | |||
4643 | : CK_IntegralToFloating, | |||
4644 | VK_PRValue, /*BasePath=*/nullptr, CCK) | |||
4645 | .get(); | |||
4646 | } else { | |||
4647 | assert(ToType->isIntegerType())(static_cast <bool> (ToType->isIntegerType()) ? void (0) : __assert_fail ("ToType->isIntegerType()", "clang/lib/Sema/SemaExprCXX.cpp" , 4647, __extension__ __PRETTY_FUNCTION__)); | |||
4648 | From = ImpCastExprToType(From, ToType, | |||
4649 | isFloatingComplex ? CK_FloatingToIntegral | |||
4650 | : CK_IntegralCast, | |||
4651 | VK_PRValue, /*BasePath=*/nullptr, CCK) | |||
4652 | .get(); | |||
4653 | } | |||
4654 | } | |||
4655 | break; | |||
4656 | ||||
4657 | case ICK_Block_Pointer_Conversion: { | |||
4658 | LangAS AddrSpaceL = | |||
4659 | ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); | |||
4660 | LangAS AddrSpaceR = | |||
4661 | FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); | |||
4662 | assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&(static_cast <bool> (Qualifiers::isAddressSpaceSupersetOf (AddrSpaceL, AddrSpaceR) && "Invalid cast") ? void (0 ) : __assert_fail ("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\"" , "clang/lib/Sema/SemaExprCXX.cpp", 4663, __extension__ __PRETTY_FUNCTION__ )) | |||
4663 | "Invalid cast")(static_cast <bool> (Qualifiers::isAddressSpaceSupersetOf (AddrSpaceL, AddrSpaceR) && "Invalid cast") ? void (0 ) : __assert_fail ("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\"" , "clang/lib/Sema/SemaExprCXX.cpp", 4663, __extension__ __PRETTY_FUNCTION__ )); | |||
4664 | CastKind Kind = | |||
4665 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | |||
4666 | From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind, | |||
4667 | VK_PRValue, /*BasePath=*/nullptr, CCK) | |||
4668 | .get(); | |||
4669 | break; | |||
4670 | } | |||
4671 | ||||
4672 | case ICK_TransparentUnionConversion: { | |||
4673 | ExprResult FromRes = From; | |||
4674 | Sema::AssignConvertType ConvTy = | |||
4675 | CheckTransparentUnionArgumentConstraints(ToType, FromRes); | |||
4676 | if (FromRes.isInvalid()) | |||
4677 | return ExprError(); | |||
4678 | From = FromRes.get(); | |||
4679 | assert ((ConvTy == Sema::Compatible) &&(static_cast <bool> ((ConvTy == Sema::Compatible) && "Improper transparent union conversion") ? void (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\"" , "clang/lib/Sema/SemaExprCXX.cpp", 4680, __extension__ __PRETTY_FUNCTION__ )) | |||
4680 | "Improper transparent union conversion")(static_cast <bool> ((ConvTy == Sema::Compatible) && "Improper transparent union conversion") ? void (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\"" , "clang/lib/Sema/SemaExprCXX.cpp", 4680, __extension__ __PRETTY_FUNCTION__ )); | |||
4681 | (void)ConvTy; | |||
4682 | break; | |||
4683 | } | |||
4684 | ||||
4685 | case ICK_Zero_Event_Conversion: | |||
4686 | case ICK_Zero_Queue_Conversion: | |||
4687 | From = ImpCastExprToType(From, ToType, | |||
4688 | CK_ZeroToOCLOpaqueType, | |||
4689 | From->getValueKind()).get(); | |||
4690 | break; | |||
4691 | ||||
4692 | case ICK_Lvalue_To_Rvalue: | |||
4693 | case ICK_Array_To_Pointer: | |||
4694 | case ICK_Function_To_Pointer: | |||
4695 | case ICK_Function_Conversion: | |||
4696 | case ICK_Qualification: | |||
4697 | case ICK_Num_Conversion_Kinds: | |||
4698 | case ICK_C_Only_Conversion: | |||
4699 | case ICK_Incompatible_Pointer_Conversion: | |||
4700 | llvm_unreachable("Improper second standard conversion")::llvm::llvm_unreachable_internal("Improper second standard conversion" , "clang/lib/Sema/SemaExprCXX.cpp", 4700); | |||
4701 | } | |||
4702 | ||||
4703 | switch (SCS.Third) { | |||
4704 | case ICK_Identity: | |||
4705 | // Nothing to do. | |||
4706 | break; | |||
4707 | ||||
4708 | case ICK_Function_Conversion: | |||
4709 | // If both sides are functions (or pointers/references to them), there could | |||
4710 | // be incompatible exception declarations. | |||
4711 | if (CheckExceptionSpecCompatibility(From, ToType)) | |||
4712 | return ExprError(); | |||
4713 | ||||
4714 | From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue, | |||
4715 | /*BasePath=*/nullptr, CCK) | |||
4716 | .get(); | |||
4717 | break; | |||
4718 | ||||
4719 | case ICK_Qualification: { | |||
4720 | ExprValueKind VK = From->getValueKind(); | |||
4721 | CastKind CK = CK_NoOp; | |||
4722 | ||||
4723 | if (ToType->isReferenceType() && | |||
4724 | ToType->getPointeeType().getAddressSpace() != | |||
4725 | From->getType().getAddressSpace()) | |||
4726 | CK = CK_AddressSpaceConversion; | |||
4727 | ||||
4728 | if (ToType->isPointerType() && | |||
4729 | ToType->getPointeeType().getAddressSpace() != | |||
4730 | From->getType()->getPointeeType().getAddressSpace()) | |||
4731 | CK = CK_AddressSpaceConversion; | |||
4732 | ||||
4733 | if (!isCast(CCK) && | |||
4734 | !ToType->getPointeeType().getQualifiers().hasUnaligned() && | |||
4735 | From->getType()->getPointeeType().getQualifiers().hasUnaligned()) { | |||
4736 | Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned) | |||
4737 | << InitialFromType << ToType; | |||
4738 | } | |||
4739 | ||||
4740 | From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK, | |||
4741 | /*BasePath=*/nullptr, CCK) | |||
4742 | .get(); | |||
4743 | ||||
4744 | if (SCS.DeprecatedStringLiteralToCharPtr && | |||
4745 | !getLangOpts().WritableStrings) { | |||
4746 | Diag(From->getBeginLoc(), | |||
4747 | getLangOpts().CPlusPlus11 | |||
4748 | ? diag::ext_deprecated_string_literal_conversion | |||
4749 | : diag::warn_deprecated_string_literal_conversion) | |||
4750 | << ToType.getNonReferenceType(); | |||
4751 | } | |||
4752 | ||||
4753 | break; | |||
4754 | } | |||
4755 | ||||
4756 | default: | |||
4757 | llvm_unreachable("Improper third standard conversion")::llvm::llvm_unreachable_internal("Improper third standard conversion" , "clang/lib/Sema/SemaExprCXX.cpp", 4757); | |||
4758 | } | |||
4759 | ||||
4760 | // If this conversion sequence involved a scalar -> atomic conversion, perform | |||
4761 | // that conversion now. | |||
4762 | if (!ToAtomicType.isNull()) { | |||
4763 | assert(Context.hasSameType((static_cast <bool> (Context.hasSameType( ToAtomicType-> castAs<AtomicType>()->getValueType(), From->getType ())) ? void (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())" , "clang/lib/Sema/SemaExprCXX.cpp", 4764, __extension__ __PRETTY_FUNCTION__ )) | |||
4764 | ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()))(static_cast <bool> (Context.hasSameType( ToAtomicType-> castAs<AtomicType>()->getValueType(), From->getType ())) ? void (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())" , "clang/lib/Sema/SemaExprCXX.cpp", 4764, __extension__ __PRETTY_FUNCTION__ )); | |||
4765 | From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, | |||
4766 | VK_PRValue, nullptr, CCK) | |||
4767 | .get(); | |||
4768 | } | |||
4769 | ||||
4770 | // Materialize a temporary if we're implicitly converting to a reference | |||
4771 | // type. This is not required by the C++ rules but is necessary to maintain | |||
4772 | // AST invariants. | |||
4773 | if (ToType->isReferenceType() && From->isPRValue()) { | |||
4774 | ExprResult Res = TemporaryMaterializationConversion(From); | |||
4775 | if (Res.isInvalid()) | |||
4776 | return ExprError(); | |||
4777 | From = Res.get(); | |||
4778 | } | |||
4779 | ||||
4780 | // If this conversion sequence succeeded and involved implicitly converting a | |||
4781 | // _Nullable type to a _Nonnull one, complain. | |||
4782 | if (!isCast(CCK)) | |||
4783 | diagnoseNullableToNonnullConversion(ToType, InitialFromType, | |||
4784 | From->getBeginLoc()); | |||
4785 | ||||
4786 | return From; | |||
4787 | } | |||
4788 | ||||
4789 | /// Check the completeness of a type in a unary type trait. | |||
4790 | /// | |||
4791 | /// If the particular type trait requires a complete type, tries to complete | |||
4792 | /// it. If completing the type fails, a diagnostic is emitted and false | |||
4793 | /// returned. If completing the type succeeds or no completion was required, | |||
4794 | /// returns true. | |||
4795 | static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, | |||
4796 | SourceLocation Loc, | |||
4797 | QualType ArgTy) { | |||
4798 | // C++0x [meta.unary.prop]p3: | |||
4799 | // For all of the class templates X declared in this Clause, instantiating | |||
4800 | // that template with a template argument that is a class template | |||
4801 | // specialization may result in the implicit instantiation of the template | |||
4802 | // argument if and only if the semantics of X require that the argument | |||
4803 | // must be a complete type. | |||
4804 | // We apply this rule to all the type trait expressions used to implement | |||
4805 | // these class templates. We also try to follow any GCC documented behavior | |||
4806 | // in these expressions to ensure portability of standard libraries. | |||
4807 | switch (UTT) { | |||
4808 | default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "clang/lib/Sema/SemaExprCXX.cpp" , 4808); | |||
4809 | // is_complete_type somewhat obviously cannot require a complete type. | |||
4810 | case UTT_IsCompleteType: | |||
4811 | // Fall-through | |||
4812 | ||||
4813 | // These traits are modeled on the type predicates in C++0x | |||
4814 | // [meta.unary.cat] and [meta.unary.comp]. They are not specified as | |||
4815 | // requiring a complete type, as whether or not they return true cannot be | |||
4816 | // impacted by the completeness of the type. | |||
4817 | case UTT_IsVoid: | |||
4818 | case UTT_IsIntegral: | |||
4819 | case UTT_IsFloatingPoint: | |||
4820 | case UTT_IsArray: | |||
4821 | case UTT_IsBoundedArray: | |||
4822 | case UTT_IsPointer: | |||
4823 | case UTT_IsNullPointer: | |||
4824 | case UTT_IsReferenceable: | |||
4825 | case UTT_IsLvalueReference: | |||
4826 | case UTT_IsRvalueReference: | |||
4827 | case UTT_IsMemberFunctionPointer: | |||
4828 | case UTT_IsMemberObjectPointer: | |||
4829 | case UTT_IsEnum: | |||
4830 | case UTT_IsScopedEnum: | |||
4831 | case UTT_IsUnion: | |||
4832 | case UTT_IsClass: | |||
4833 | case UTT_IsFunction: | |||
4834 | case UTT_IsReference: | |||
4835 | case UTT_IsArithmetic: | |||
4836 | case UTT_IsFundamental: | |||
4837 | case UTT_IsObject: | |||
4838 | case UTT_IsScalar: | |||
4839 | case UTT_IsCompound: | |||
4840 | case UTT_IsMemberPointer: | |||
4841 | // Fall-through | |||
4842 | ||||
4843 | // These traits are modeled on type predicates in C++0x [meta.unary.prop] | |||
4844 | // which requires some of its traits to have the complete type. However, | |||
4845 | // the completeness of the type cannot impact these traits' semantics, and | |||
4846 | // so they don't require it. This matches the comments on these traits in | |||
4847 | // Table 49. | |||
4848 | case UTT_IsConst: | |||
4849 | case UTT_IsVolatile: | |||
4850 | case UTT_IsSigned: | |||
4851 | case UTT_IsUnboundedArray: | |||
4852 | case UTT_IsUnsigned: | |||
4853 | ||||
4854 | // This type trait always returns false, checking the type is moot. | |||
4855 | case UTT_IsInterfaceClass: | |||
4856 | return true; | |||
4857 | ||||
4858 | // C++14 [meta.unary.prop]: | |||
4859 | // If T is a non-union class type, T shall be a complete type. | |||
4860 | case UTT_IsEmpty: | |||
4861 | case UTT_IsPolymorphic: | |||
4862 | case UTT_IsAbstract: | |||
4863 | if (const auto *RD = ArgTy->getAsCXXRecordDecl()) | |||
4864 | if (!RD->isUnion()) | |||
4865 | return !S.RequireCompleteType( | |||
4866 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); | |||
4867 | return true; | |||
4868 | ||||
4869 | // C++14 [meta.unary.prop]: | |||
4870 | // If T is a class type, T shall be a complete type. | |||
4871 | case UTT_IsFinal: | |||
4872 | case UTT_IsSealed: | |||
4873 | if (ArgTy->getAsCXXRecordDecl()) | |||
4874 | return !S.RequireCompleteType( | |||
4875 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); | |||
4876 | return true; | |||
4877 | ||||
4878 | // LWG3823: T shall be an array type, a complete type, or cv void. | |||
4879 | case UTT_IsAggregate: | |||
4880 | if (ArgTy->isArrayType() || ArgTy->isVoidType()) | |||
4881 | return true; | |||
4882 | ||||
4883 | return !S.RequireCompleteType( | |||
4884 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); | |||
4885 | ||||
4886 | // C++1z [meta.unary.prop]: | |||
4887 | // remove_all_extents_t<T> shall be a complete type or cv void. | |||
4888 | case UTT_IsTrivial: | |||
4889 | case UTT_IsTriviallyCopyable: | |||
4890 | case UTT_IsStandardLayout: | |||
4891 | case UTT_IsPOD: | |||
4892 | case UTT_IsLiteral: | |||
4893 | // By analogy, is_trivially_relocatable imposes the same constraints. | |||
4894 | case UTT_IsTriviallyRelocatable: | |||
4895 | // Per the GCC type traits documentation, T shall be a complete type, cv void, | |||
4896 | // or an array of unknown bound. But GCC actually imposes the same constraints | |||
4897 | // as above. | |||
4898 | case UTT_HasNothrowAssign: | |||
4899 | case UTT_HasNothrowMoveAssign: | |||
4900 | case UTT_HasNothrowConstructor: | |||
4901 | case UTT_HasNothrowCopy: | |||
4902 | case UTT_HasTrivialAssign: | |||
4903 | case UTT_HasTrivialMoveAssign: | |||
4904 | case UTT_HasTrivialDefaultConstructor: | |||
4905 | case UTT_HasTrivialMoveConstructor: | |||
4906 | case UTT_HasTrivialCopy: | |||
4907 | case UTT_HasTrivialDestructor: | |||
4908 | case UTT_HasVirtualDestructor: | |||
4909 | ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); | |||
4910 | [[fallthrough]]; | |||
4911 | ||||
4912 | // C++1z [meta.unary.prop]: | |||
4913 | // T shall be a complete type, cv void, or an array of unknown bound. | |||
4914 | case UTT_IsDestructible: | |||
4915 | case UTT_IsNothrowDestructible: | |||
4916 | case UTT_IsTriviallyDestructible: | |||
4917 | case UTT_HasUniqueObjectRepresentations: | |||
4918 | if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) | |||
4919 | return true; | |||
4920 | ||||
4921 | return !S.RequireCompleteType( | |||
4922 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); | |||
4923 | } | |||
4924 | } | |||
4925 | ||||
4926 | static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, | |||
4927 | Sema &Self, SourceLocation KeyLoc, ASTContext &C, | |||
4928 | bool (CXXRecordDecl::*HasTrivial)() const, | |||
4929 | bool (CXXRecordDecl::*HasNonTrivial)() const, | |||
4930 | bool (CXXMethodDecl::*IsDesiredOp)() const) | |||
4931 | { | |||
4932 | CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | |||
4933 | if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) | |||
4934 | return true; | |||
4935 | ||||
4936 | DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); | |||
4937 | DeclarationNameInfo NameInfo(Name, KeyLoc); | |||
4938 | LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); | |||
4939 | if (Self.LookupQualifiedName(Res, RD)) { | |||
4940 | bool FoundOperator = false; | |||
4941 | Res.suppressDiagnostics(); | |||
4942 | for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); | |||
4943 | Op != OpEnd; ++Op) { | |||
4944 | if (isa<FunctionTemplateDecl>(*Op)) | |||
4945 | continue; | |||
4946 | ||||
4947 | CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); | |||
4948 | if((Operator->*IsDesiredOp)()) { | |||
4949 | FoundOperator = true; | |||
4950 | auto *CPT = Operator->getType()->castAs<FunctionProtoType>(); | |||
4951 | CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); | |||
4952 | if (!CPT || !CPT->isNothrow()) | |||
4953 | return false; | |||
4954 | } | |||
4955 | } | |||
4956 | return FoundOperator; | |||
4957 | } | |||
4958 | return false; | |||
4959 | } | |||
4960 | ||||
4961 | static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, | |||
4962 | SourceLocation KeyLoc, QualType T) { | |||
4963 | assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")(static_cast <bool> (!T->isDependentType() && "Cannot evaluate traits of dependent type") ? void (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\"" , "clang/lib/Sema/SemaExprCXX.cpp", 4963, __extension__ __PRETTY_FUNCTION__ )); | |||
4964 | ||||
4965 | ASTContext &C = Self.Context; | |||
4966 | switch(UTT) { | |||
4967 | default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "clang/lib/Sema/SemaExprCXX.cpp" , 4967); | |||
4968 | // Type trait expressions corresponding to the primary type category | |||
4969 | // predicates in C++0x [meta.unary.cat]. | |||
4970 | case UTT_IsVoid: | |||
4971 | return T->isVoidType(); | |||
4972 | case UTT_IsIntegral: | |||
4973 | return T->isIntegralType(C); | |||
4974 | case UTT_IsFloatingPoint: | |||
4975 | return T->isFloatingType(); | |||
4976 | case UTT_IsArray: | |||
4977 | return T->isArrayType(); | |||
4978 | case UTT_IsBoundedArray: | |||
4979 | if (!T->isVariableArrayType()) { | |||
4980 | return T->isArrayType() && !T->isIncompleteArrayType(); | |||
4981 | } | |||
4982 | ||||
4983 | Self.Diag(KeyLoc, diag::err_vla_unsupported) | |||
4984 | << 1 << tok::kw___is_bounded_array; | |||
4985 | return false; | |||
4986 | case UTT_IsUnboundedArray: | |||
4987 | if (!T->isVariableArrayType()) { | |||
4988 | return T->isIncompleteArrayType(); | |||
4989 | } | |||
4990 | ||||
4991 | Self.Diag(KeyLoc, diag::err_vla_unsupported) | |||
4992 | << 1 << tok::kw___is_unbounded_array; | |||
4993 | return false; | |||
4994 | case UTT_IsPointer: | |||
4995 | return T->isAnyPointerType(); | |||
4996 | case UTT_IsNullPointer: | |||
4997 | return T->isNullPtrType(); | |||
4998 | case UTT_IsLvalueReference: | |||
4999 | return T->isLValueReferenceType(); | |||
5000 | case UTT_IsRvalueReference: | |||
5001 | return T->isRValueReferenceType(); | |||
5002 | case UTT_IsMemberFunctionPointer: | |||
5003 | return T->isMemberFunctionPointerType(); | |||
5004 | case UTT_IsMemberObjectPointer: | |||
5005 | return T->isMemberDataPointerType(); | |||
5006 | case UTT_IsEnum: | |||
5007 | return T->isEnumeralType(); | |||
5008 | case UTT_IsScopedEnum: | |||
5009 | return T->isScopedEnumeralType(); | |||
5010 | case UTT_IsUnion: | |||
5011 | return T->isUnionType(); | |||
5012 | case UTT_IsClass: | |||
5013 | return T->isClassType() || T->isStructureType() || T->isInterfaceType(); | |||
5014 | case UTT_IsFunction: | |||
5015 | return T->isFunctionType(); | |||
5016 | ||||
5017 | // Type trait expressions which correspond to the convenient composition | |||
5018 | // predicates in C++0x [meta.unary.comp]. | |||
5019 | case UTT_IsReference: | |||
5020 | return T->isReferenceType(); | |||
5021 | case UTT_IsArithmetic: | |||
5022 | return T->isArithmeticType() && !T->isEnumeralType(); | |||
5023 | case UTT_IsFundamental: | |||
5024 | return T->isFundamentalType(); | |||
5025 | case UTT_IsObject: | |||
5026 | return T->isObjectType(); | |||
5027 | case UTT_IsScalar: | |||
5028 | // Note: semantic analysis depends on Objective-C lifetime types to be | |||
5029 | // considered scalar types. However, such types do not actually behave | |||
5030 | // like scalar types at run time (since they may require retain/release | |||
5031 | // operations), so we report them as non-scalar. | |||
5032 | if (T->isObjCLifetimeType()) { | |||
5033 | switch (T.getObjCLifetime()) { | |||
5034 | case Qualifiers::OCL_None: | |||
5035 | case Qualifiers::OCL_ExplicitNone: | |||
5036 | return true; | |||
5037 | ||||
5038 | case Qualifiers::OCL_Strong: | |||
5039 | case Qualifiers::OCL_Weak: | |||
5040 | case Qualifiers::OCL_Autoreleasing: | |||
5041 | return false; | |||
5042 | } | |||
5043 | } | |||
5044 | ||||
5045 | return T->isScalarType(); | |||
5046 | case UTT_IsCompound: | |||
5047 | return T->isCompoundType(); | |||
5048 | case UTT_IsMemberPointer: | |||
5049 | return T->isMemberPointerType(); | |||
5050 | ||||
5051 | // Type trait expressions which correspond to the type property predicates | |||
5052 | // in C++0x [meta.unary.prop]. | |||
5053 | case UTT_IsConst: | |||
5054 | return T.isConstQualified(); | |||
5055 | case UTT_IsVolatile: | |||
5056 | return T.isVolatileQualified(); | |||
5057 | case UTT_IsTrivial: | |||
5058 | return T.isTrivialType(C); | |||
5059 | case UTT_IsTriviallyCopyable: | |||
5060 | return T.isTriviallyCopyableType(C); | |||
5061 | case UTT_IsStandardLayout: | |||
5062 | return T->isStandardLayoutType(); | |||
5063 | case UTT_IsPOD: | |||
5064 | return T.isPODType(C); | |||
5065 | case UTT_IsLiteral: | |||
5066 | return T->isLiteralType(C); | |||
5067 | case UTT_IsEmpty: | |||
5068 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
5069 | return !RD->isUnion() && RD->isEmpty(); | |||
5070 | return false; | |||
5071 | case UTT_IsPolymorphic: | |||
5072 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
5073 | return !RD->isUnion() && RD->isPolymorphic(); | |||
5074 | return false; | |||
5075 | case UTT_IsAbstract: | |||
5076 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
5077 | return !RD->isUnion() && RD->isAbstract(); | |||
5078 | return false; | |||
5079 | case UTT_IsAggregate: | |||
5080 | // Report vector extensions and complex types as aggregates because they | |||
5081 | // support aggregate initialization. GCC mirrors this behavior for vectors | |||
5082 | // but not _Complex. | |||
5083 | return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || | |||
5084 | T->isAnyComplexType(); | |||
5085 | // __is_interface_class only returns true when CL is invoked in /CLR mode and | |||
5086 | // even then only when it is used with the 'interface struct ...' syntax | |||
5087 | // Clang doesn't support /CLR which makes this type trait moot. | |||
5088 | case UTT_IsInterfaceClass: | |||
5089 | return false; | |||
5090 | case UTT_IsFinal: | |||
5091 | case UTT_IsSealed: | |||
5092 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
5093 | return RD->hasAttr<FinalAttr>(); | |||
5094 | return false; | |||
5095 | case UTT_IsSigned: | |||
5096 | // Enum types should always return false. | |||
5097 | // Floating points should always return true. | |||
5098 | return T->isFloatingType() || | |||
5099 | (T->isSignedIntegerType() && !T->isEnumeralType()); | |||
5100 | case UTT_IsUnsigned: | |||
5101 | // Enum types should always return false. | |||
5102 | return T->isUnsignedIntegerType() && !T->isEnumeralType(); | |||
5103 | ||||
5104 | // Type trait expressions which query classes regarding their construction, | |||
5105 | // destruction, and copying. Rather than being based directly on the | |||
5106 | // related type predicates in the standard, they are specified by both | |||
5107 | // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those | |||
5108 | // specifications. | |||
5109 | // | |||
5110 | // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html | |||
5111 | // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index | |||
5112 | // | |||
5113 | // Note that these builtins do not behave as documented in g++: if a class | |||
5114 | // has both a trivial and a non-trivial special member of a particular kind, | |||
5115 | // they return false! For now, we emulate this behavior. | |||
5116 | // FIXME: This appears to be a g++ bug: more complex cases reveal that it | |||
5117 | // does not correctly compute triviality in the presence of multiple special | |||
5118 | // members of the same kind. Revisit this once the g++ bug is fixed. | |||
5119 | case UTT_HasTrivialDefaultConstructor: | |||
5120 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
5121 | // If __is_pod (type) is true then the trait is true, else if type is | |||
5122 | // a cv class or union type (or array thereof) with a trivial default | |||
5123 | // constructor ([class.ctor]) then the trait is true, else it is false. | |||
5124 | if (T.isPODType(C)) | |||
5125 | return true; | |||
5126 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) | |||
5127 | return RD->hasTrivialDefaultConstructor() && | |||
5128 | !RD->hasNonTrivialDefaultConstructor(); | |||
5129 | return false; | |||
5130 | case UTT_HasTrivialMoveConstructor: | |||
5131 | // This trait is implemented by MSVC 2012 and needed to parse the | |||
5132 | // standard library headers. Specifically this is used as the logic | |||
5133 | // behind std::is_trivially_move_constructible (20.9.4.3). | |||
5134 | if (T.isPODType(C)) | |||
5135 | return true; | |||
5136 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) | |||
5137 | return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); | |||
5138 | return false; | |||
5139 | case UTT_HasTrivialCopy: | |||
5140 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
5141 | // If __is_pod (type) is true or type is a reference type then | |||
5142 | // the trait is true, else if type is a cv class or union type | |||
5143 | // with a trivial copy constructor ([class.copy]) then the trait | |||
5144 | // is true, else it is false. | |||
5145 | if (T.isPODType(C) || T->isReferenceType()) | |||
5146 | return true; | |||
5147 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
5148 | return RD->hasTrivialCopyConstructor() && | |||
5149 | !RD->hasNonTrivialCopyConstructor(); | |||
5150 | return false; | |||
5151 | case UTT_HasTrivialMoveAssign: | |||
5152 | // This trait is implemented by MSVC 2012 and needed to parse the | |||
5153 | // standard library headers. Specifically it is used as the logic | |||
5154 | // behind std::is_trivially_move_assignable (20.9.4.3) | |||
5155 | if (T.isPODType(C)) | |||
5156 | return true; | |||
5157 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) | |||
5158 | return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); | |||
5159 | return false; | |||
5160 | case UTT_HasTrivialAssign: | |||
5161 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
5162 | // If type is const qualified or is a reference type then the | |||
5163 | // trait is false. Otherwise if __is_pod (type) is true then the | |||
5164 | // trait is true, else if type is a cv class or union type with | |||
5165 | // a trivial copy assignment ([class.copy]) then the trait is | |||
5166 | // true, else it is false. | |||
5167 | // Note: the const and reference restrictions are interesting, | |||
5168 | // given that const and reference members don't prevent a class | |||
5169 | // from having a trivial copy assignment operator (but do cause | |||
5170 | // errors if the copy assignment operator is actually used, q.v. | |||
5171 | // [class.copy]p12). | |||
5172 | ||||
5173 | if (T.isConstQualified()) | |||
5174 | return false; | |||
5175 | if (T.isPODType(C)) | |||
5176 | return true; | |||
5177 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
5178 | return RD->hasTrivialCopyAssignment() && | |||
5179 | !RD->hasNonTrivialCopyAssignment(); | |||
5180 | return false; | |||
5181 | case UTT_IsDestructible: | |||
5182 | case UTT_IsTriviallyDestructible: | |||
5183 | case UTT_IsNothrowDestructible: | |||
5184 | // C++14 [meta.unary.prop]: | |||
5185 | // For reference types, is_destructible<T>::value is true. | |||
5186 | if (T->isReferenceType()) | |||
5187 | return true; | |||
5188 | ||||
5189 | // Objective-C++ ARC: autorelease types don't require destruction. | |||
5190 | if (T->isObjCLifetimeType() && | |||
5191 | T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) | |||
5192 | return true; | |||
5193 | ||||
5194 | // C++14 [meta.unary.prop]: | |||
5195 | // For incomplete types and function types, is_destructible<T>::value is | |||
5196 | // false. | |||
5197 | if (T->isIncompleteType() || T->isFunctionType()) | |||
5198 | return false; | |||
5199 | ||||
5200 | // A type that requires destruction (via a non-trivial destructor or ARC | |||
5201 | // lifetime semantics) is not trivially-destructible. | |||
5202 | if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) | |||
5203 | return false; | |||
5204 | ||||
5205 | // C++14 [meta.unary.prop]: | |||
5206 | // For object types and given U equal to remove_all_extents_t<T>, if the | |||
5207 | // expression std::declval<U&>().~U() is well-formed when treated as an | |||
5208 | // unevaluated operand (Clause 5), then is_destructible<T>::value is true | |||
5209 | if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { | |||
5210 | CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); | |||
5211 | if (!Destructor) | |||
5212 | return false; | |||
5213 | // C++14 [dcl.fct.def.delete]p2: | |||
5214 | // A program that refers to a deleted function implicitly or | |||
5215 | // explicitly, other than to declare it, is ill-formed. | |||
5216 | if (Destructor->isDeleted()) | |||
5217 | return false; | |||
5218 | if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) | |||
5219 | return false; | |||
5220 | if (UTT == UTT_IsNothrowDestructible) { | |||
5221 | auto *CPT = Destructor->getType()->castAs<FunctionProtoType>(); | |||
5222 | CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); | |||
5223 | if (!CPT || !CPT->isNothrow()) | |||
5224 | return false; | |||
5225 | } | |||
5226 | } | |||
5227 | return true; | |||
5228 | ||||
5229 | case UTT_HasTrivialDestructor: | |||
5230 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html | |||
5231 | // If __is_pod (type) is true or type is a reference type | |||
5232 | // then the trait is true, else if type is a cv class or union | |||
5233 | // type (or array thereof) with a trivial destructor | |||
5234 | // ([class.dtor]) then the trait is true, else it is | |||
5235 | // false. | |||
5236 | if (T.isPODType(C) || T->isReferenceType()) | |||
5237 | return true; | |||
5238 | ||||
5239 | // Objective-C++ ARC: autorelease types don't require destruction. | |||
5240 | if (T->isObjCLifetimeType() && | |||
5241 | T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) | |||
5242 | return true; | |||
5243 | ||||
5244 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) | |||
5245 | return RD->hasTrivialDestructor(); | |||
5246 | return false; | |||
5247 | // TODO: Propagate nothrowness for implicitly declared special members. | |||
5248 | case UTT_HasNothrowAssign: | |||
5249 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
5250 | // If type is const qualified or is a reference type then the | |||
5251 | // trait is false. Otherwise if __has_trivial_assign (type) | |||
5252 | // is true then the trait is true, else if type is a cv class | |||
5253 | // or union type with copy assignment operators that are known | |||
5254 | // not to throw an exception then the trait is true, else it is | |||
5255 | // false. | |||
5256 | if (C.getBaseElementType(T).isConstQualified()) | |||
5257 | return false; | |||
5258 | if (T->isReferenceType()) | |||
5259 | return false; | |||
5260 | if (T.isPODType(C) || T->isObjCLifetimeType()) | |||
5261 | return true; | |||
5262 | ||||
5263 | if (const RecordType *RT = T->getAs<RecordType>()) | |||
5264 | return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, | |||
5265 | &CXXRecordDecl::hasTrivialCopyAssignment, | |||
5266 | &CXXRecordDecl::hasNonTrivialCopyAssignment, | |||
5267 | &CXXMethodDecl::isCopyAssignmentOperator); | |||
5268 | return false; | |||
5269 | case UTT_HasNothrowMoveAssign: | |||
5270 | // This trait is implemented by MSVC 2012 and needed to parse the | |||
5271 | // standard library headers. Specifically this is used as the logic | |||
5272 | // behind std::is_nothrow_move_assignable (20.9.4.3). | |||
5273 | if (T.isPODType(C)) | |||
5274 | return true; | |||
5275 | ||||
5276 | if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) | |||
5277 | return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, | |||
5278 | &CXXRecordDecl::hasTrivialMoveAssignment, | |||
5279 | &CXXRecordDecl::hasNonTrivialMoveAssignment, | |||
5280 | &CXXMethodDecl::isMoveAssignmentOperator); | |||
5281 | return false; | |||
5282 | case UTT_HasNothrowCopy: | |||
5283 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
5284 | // If __has_trivial_copy (type) is true then the trait is true, else | |||
5285 | // if type is a cv class or union type with copy constructors that are | |||
5286 | // known not to throw an exception then the trait is true, else it is | |||
5287 | // false. | |||
5288 | if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) | |||
5289 | return true; | |||
5290 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { | |||
5291 | if (RD->hasTrivialCopyConstructor() && | |||
5292 | !RD->hasNonTrivialCopyConstructor()) | |||
5293 | return true; | |||
5294 | ||||
5295 | bool FoundConstructor = false; | |||
5296 | unsigned FoundTQs; | |||
5297 | for (const auto *ND : Self.LookupConstructors(RD)) { | |||
5298 | // A template constructor is never a copy constructor. | |||
5299 | // FIXME: However, it may actually be selected at the actual overload | |||
5300 | // resolution point. | |||
5301 | if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) | |||
5302 | continue; | |||
5303 | // UsingDecl itself is not a constructor | |||
5304 | if (isa<UsingDecl>(ND)) | |||
5305 | continue; | |||
5306 | auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); | |||
5307 | if (Constructor->isCopyConstructor(FoundTQs)) { | |||
5308 | FoundConstructor = true; | |||
5309 | auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); | |||
5310 | CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); | |||
5311 | if (!CPT) | |||
5312 | return false; | |||
5313 | // TODO: check whether evaluating default arguments can throw. | |||
5314 | // For now, we'll be conservative and assume that they can throw. | |||
5315 | if (!CPT->isNothrow() || CPT->getNumParams() > 1) | |||
5316 | return false; | |||
5317 | } | |||
5318 | } | |||
5319 | ||||
5320 | return FoundConstructor; | |||
5321 | } | |||
5322 | return false; | |||
5323 | case UTT_HasNothrowConstructor: | |||
5324 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html | |||
5325 | // If __has_trivial_constructor (type) is true then the trait is | |||
5326 | // true, else if type is a cv class or union type (or array | |||
5327 | // thereof) with a default constructor that is known not to | |||
5328 | // throw an exception then the trait is true, else it is false. | |||
5329 | if (T.isPODType(C) || T->isObjCLifetimeType()) | |||
5330 | return true; | |||
5331 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { | |||
5332 | if (RD->hasTrivialDefaultConstructor() && | |||
5333 | !RD->hasNonTrivialDefaultConstructor()) | |||
5334 | return true; | |||
5335 | ||||
5336 | bool FoundConstructor = false; | |||
5337 | for (const auto *ND : Self.LookupConstructors(RD)) { | |||
5338 | // FIXME: In C++0x, a constructor template can be a default constructor. | |||
5339 | if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) | |||
5340 | continue; | |||
5341 | // UsingDecl itself is not a constructor | |||
5342 | if (isa<UsingDecl>(ND)) | |||
5343 | continue; | |||
5344 | auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); | |||
5345 | if (Constructor->isDefaultConstructor()) { | |||
5346 | FoundConstructor = true; | |||
5347 | auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); | |||
5348 | CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); | |||
5349 | if (!CPT) | |||
5350 | return false; | |||
5351 | // FIXME: check whether evaluating default arguments can throw. | |||
5352 | // For now, we'll be conservative and assume that they can throw. | |||
5353 | if (!CPT->isNothrow() || CPT->getNumParams() > 0) | |||
5354 | return false; | |||
5355 | } | |||
5356 | } | |||
5357 | return FoundConstructor; | |||
5358 | } | |||
5359 | return false; | |||
5360 | case UTT_HasVirtualDestructor: | |||
5361 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
5362 | // If type is a class type with a virtual destructor ([class.dtor]) | |||
5363 | // then the trait is true, else it is false. | |||
5364 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
5365 | if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) | |||
5366 | return Destructor->isVirtual(); | |||
5367 | return false; | |||
5368 | ||||
5369 | // These type trait expressions are modeled on the specifications for the | |||
5370 | // Embarcadero C++0x type trait functions: | |||
5371 | // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index | |||
5372 | case UTT_IsCompleteType: | |||
5373 | // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): | |||
5374 | // Returns True if and only if T is a complete type at the point of the | |||
5375 | // function call. | |||
5376 | return !T->isIncompleteType(); | |||
5377 | case UTT_HasUniqueObjectRepresentations: | |||
5378 | return C.hasUniqueObjectRepresentations(T); | |||
5379 | case UTT_IsTriviallyRelocatable: | |||
5380 | return T.isTriviallyRelocatableType(C); | |||
5381 | case UTT_IsReferenceable: | |||
5382 | return T.isReferenceable(); | |||
5383 | } | |||
5384 | } | |||
5385 | ||||
5386 | static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, | |||
5387 | QualType RhsT, SourceLocation KeyLoc); | |||
5388 | ||||
5389 | static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, | |||
5390 | ArrayRef<TypeSourceInfo *> Args, | |||
5391 | SourceLocation RParenLoc) { | |||
5392 | if (Kind <= UTT_Last) | |||
5393 | return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType()); | |||
5394 | ||||
5395 | // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible | |||
5396 | // traits to avoid duplication. | |||
5397 | if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary) | |||
5398 | return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(), | |||
5399 | Args[1]->getType(), RParenLoc); | |||
5400 | ||||
5401 | switch (Kind) { | |||
5402 | case clang::BTT_ReferenceBindsToTemporary: | |||
5403 | case clang::TT_IsConstructible: | |||
5404 | case clang::TT_IsNothrowConstructible: | |||
5405 | case clang::TT_IsTriviallyConstructible: { | |||
5406 | // C++11 [meta.unary.prop]: | |||
5407 | // is_trivially_constructible is defined as: | |||
5408 | // | |||
5409 | // is_constructible<T, Args...>::value is true and the variable | |||
5410 | // definition for is_constructible, as defined below, is known to call | |||
5411 | // no operation that is not trivial. | |||
5412 | // | |||
5413 | // The predicate condition for a template specialization | |||
5414 | // is_constructible<T, Args...> shall be satisfied if and only if the | |||
5415 | // following variable definition would be well-formed for some invented | |||
5416 | // variable t: | |||
5417 | // | |||
5418 | // T t(create<Args>()...); | |||
5419 | assert(!Args.empty())(static_cast <bool> (!Args.empty()) ? void (0) : __assert_fail ("!Args.empty()", "clang/lib/Sema/SemaExprCXX.cpp", 5419, __extension__ __PRETTY_FUNCTION__)); | |||
5420 | ||||
5421 | // Precondition: T and all types in the parameter pack Args shall be | |||
5422 | // complete types, (possibly cv-qualified) void, or arrays of | |||
5423 | // unknown bound. | |||
5424 | for (const auto *TSI : Args) { | |||
5425 | QualType ArgTy = TSI->getType(); | |||
5426 | if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) | |||
5427 | continue; | |||
5428 | ||||
5429 | if (S.RequireCompleteType(KWLoc, ArgTy, | |||
5430 | diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5431 | return false; | |||
5432 | } | |||
5433 | ||||
5434 | // Make sure the first argument is not incomplete nor a function type. | |||
5435 | QualType T = Args[0]->getType(); | |||
5436 | if (T->isIncompleteType() || T->isFunctionType()) | |||
5437 | return false; | |||
5438 | ||||
5439 | // Make sure the first argument is not an abstract type. | |||
5440 | CXXRecordDecl *RD = T->getAsCXXRecordDecl(); | |||
5441 | if (RD && RD->isAbstract()) | |||
5442 | return false; | |||
5443 | ||||
5444 | llvm::BumpPtrAllocator OpaqueExprAllocator; | |||
5445 | SmallVector<Expr *, 2> ArgExprs; | |||
5446 | ArgExprs.reserve(Args.size() - 1); | |||
5447 | for (unsigned I = 1, N = Args.size(); I != N; ++I) { | |||
5448 | QualType ArgTy = Args[I]->getType(); | |||
5449 | if (ArgTy->isObjectType() || ArgTy->isFunctionType()) | |||
5450 | ArgTy = S.Context.getRValueReferenceType(ArgTy); | |||
5451 | ArgExprs.push_back( | |||
5452 | new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>()) | |||
5453 | OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(), | |||
5454 | ArgTy.getNonLValueExprType(S.Context), | |||
5455 | Expr::getValueKindForType(ArgTy))); | |||
5456 | } | |||
5457 | ||||
5458 | // Perform the initialization in an unevaluated context within a SFINAE | |||
5459 | // trap at translation unit scope. | |||
5460 | EnterExpressionEvaluationContext Unevaluated( | |||
5461 | S, Sema::ExpressionEvaluationContext::Unevaluated); | |||
5462 | Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); | |||
5463 | Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); | |||
5464 | InitializedEntity To( | |||
5465 | InitializedEntity::InitializeTemporary(S.Context, Args[0])); | |||
5466 | InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, | |||
5467 | RParenLoc)); | |||
5468 | InitializationSequence Init(S, To, InitKind, ArgExprs); | |||
5469 | if (Init.Failed()) | |||
5470 | return false; | |||
5471 | ||||
5472 | ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); | |||
5473 | if (Result.isInvalid() || SFINAE.hasErrorOccurred()) | |||
5474 | return false; | |||
5475 | ||||
5476 | if (Kind == clang::TT_IsConstructible) | |||
5477 | return true; | |||
5478 | ||||
5479 | if (Kind == clang::BTT_ReferenceBindsToTemporary) { | |||
5480 | if (!T->isReferenceType()) | |||
5481 | return false; | |||
5482 | ||||
5483 | return !Init.isDirectReferenceBinding(); | |||
5484 | } | |||
5485 | ||||
5486 | if (Kind == clang::TT_IsNothrowConstructible) | |||
5487 | return S.canThrow(Result.get()) == CT_Cannot; | |||
5488 | ||||
5489 | if (Kind == clang::TT_IsTriviallyConstructible) { | |||
5490 | // Under Objective-C ARC and Weak, if the destination has non-trivial | |||
5491 | // Objective-C lifetime, this is a non-trivial construction. | |||
5492 | if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) | |||
5493 | return false; | |||
5494 | ||||
5495 | // The initialization succeeded; now make sure there are no non-trivial | |||
5496 | // calls. | |||
5497 | return !Result.get()->hasNonTrivialCall(S.Context); | |||
5498 | } | |||
5499 | ||||
5500 | llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "clang/lib/Sema/SemaExprCXX.cpp" , 5500); | |||
5501 | return false; | |||
5502 | } | |||
5503 | default: llvm_unreachable("not a TT")::llvm::llvm_unreachable_internal("not a TT", "clang/lib/Sema/SemaExprCXX.cpp" , 5503); | |||
5504 | } | |||
5505 | ||||
5506 | return false; | |||
5507 | } | |||
5508 | ||||
5509 | namespace { | |||
5510 | void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind, | |||
5511 | SourceLocation KWLoc) { | |||
5512 | TypeTrait Replacement; | |||
5513 | switch (Kind) { | |||
5514 | case UTT_HasNothrowAssign: | |||
5515 | case UTT_HasNothrowMoveAssign: | |||
5516 | Replacement = BTT_IsNothrowAssignable; | |||
5517 | break; | |||
5518 | case UTT_HasNothrowCopy: | |||
5519 | case UTT_HasNothrowConstructor: | |||
5520 | Replacement = TT_IsNothrowConstructible; | |||
5521 | break; | |||
5522 | case UTT_HasTrivialAssign: | |||
5523 | case UTT_HasTrivialMoveAssign: | |||
5524 | Replacement = BTT_IsTriviallyAssignable; | |||
5525 | break; | |||
5526 | case UTT_HasTrivialCopy: | |||
5527 | Replacement = UTT_IsTriviallyCopyable; | |||
5528 | break; | |||
5529 | case UTT_HasTrivialDefaultConstructor: | |||
5530 | case UTT_HasTrivialMoveConstructor: | |||
5531 | Replacement = TT_IsTriviallyConstructible; | |||
5532 | break; | |||
5533 | case UTT_HasTrivialDestructor: | |||
5534 | Replacement = UTT_IsTriviallyDestructible; | |||
5535 | break; | |||
5536 | default: | |||
5537 | return; | |||
5538 | } | |||
5539 | S.Diag(KWLoc, diag::warn_deprecated_builtin) | |||
5540 | << getTraitSpelling(Kind) << getTraitSpelling(Replacement); | |||
5541 | } | |||
5542 | } | |||
5543 | ||||
5544 | bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) { | |||
5545 | if (Arity && N != Arity) { | |||
5546 | Diag(Loc, diag::err_type_trait_arity) | |||
5547 | << Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc); | |||
5548 | return false; | |||
5549 | } | |||
5550 | ||||
5551 | if (!Arity && N == 0) { | |||
5552 | Diag(Loc, diag::err_type_trait_arity) | |||
5553 | << 1 << 1 << 1 << (int)N << SourceRange(Loc); | |||
5554 | return false; | |||
5555 | } | |||
5556 | return true; | |||
5557 | } | |||
5558 | ||||
5559 | ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, | |||
5560 | ArrayRef<TypeSourceInfo *> Args, | |||
5561 | SourceLocation RParenLoc) { | |||
5562 | if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size())) | |||
5563 | return ExprError(); | |||
5564 | QualType ResultType = Context.getLogicalOperationType(); | |||
5565 | ||||
5566 | if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( | |||
5567 | *this, Kind, KWLoc, Args[0]->getType())) | |||
5568 | return ExprError(); | |||
5569 | ||||
5570 | DiagnoseBuiltinDeprecation(*this, Kind, KWLoc); | |||
5571 | ||||
5572 | bool Dependent = false; | |||
5573 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { | |||
5574 | if (Args[I]->getType()->isDependentType()) { | |||
5575 | Dependent = true; | |||
5576 | break; | |||
5577 | } | |||
5578 | } | |||
5579 | ||||
5580 | bool Result = false; | |||
5581 | if (!Dependent) | |||
5582 | Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); | |||
5583 | ||||
5584 | return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args, | |||
5585 | RParenLoc, Result); | |||
5586 | } | |||
5587 | ||||
5588 | ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, | |||
5589 | ArrayRef<ParsedType> Args, | |||
5590 | SourceLocation RParenLoc) { | |||
5591 | SmallVector<TypeSourceInfo *, 4> ConvertedArgs; | |||
5592 | ConvertedArgs.reserve(Args.size()); | |||
5593 | ||||
5594 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { | |||
5595 | TypeSourceInfo *TInfo; | |||
5596 | QualType T = GetTypeFromParser(Args[I], &TInfo); | |||
5597 | if (!TInfo) | |||
5598 | TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); | |||
5599 | ||||
5600 | ConvertedArgs.push_back(TInfo); | |||
5601 | } | |||
5602 | ||||
5603 | return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); | |||
5604 | } | |||
5605 | ||||
5606 | static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, | |||
5607 | QualType RhsT, SourceLocation KeyLoc) { | |||
5608 | assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&(static_cast <bool> (!LhsT->isDependentType() && !RhsT->isDependentType() && "Cannot evaluate traits of dependent types" ) ? void (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\"" , "clang/lib/Sema/SemaExprCXX.cpp", 5609, __extension__ __PRETTY_FUNCTION__ )) | |||
5609 | "Cannot evaluate traits of dependent types")(static_cast <bool> (!LhsT->isDependentType() && !RhsT->isDependentType() && "Cannot evaluate traits of dependent types" ) ? void (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\"" , "clang/lib/Sema/SemaExprCXX.cpp", 5609, __extension__ __PRETTY_FUNCTION__ )); | |||
5610 | ||||
5611 | switch(BTT) { | |||
5612 | case BTT_IsBaseOf: { | |||
5613 | // C++0x [meta.rel]p2 | |||
5614 | // Base is a base class of Derived without regard to cv-qualifiers or | |||
5615 | // Base and Derived are not unions and name the same class type without | |||
5616 | // regard to cv-qualifiers. | |||
5617 | ||||
5618 | const RecordType *lhsRecord = LhsT->getAs<RecordType>(); | |||
5619 | const RecordType *rhsRecord = RhsT->getAs<RecordType>(); | |||
5620 | if (!rhsRecord || !lhsRecord) { | |||
5621 | const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); | |||
5622 | const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); | |||
5623 | if (!LHSObjTy || !RHSObjTy) | |||
5624 | return false; | |||
5625 | ||||
5626 | ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); | |||
5627 | ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); | |||
5628 | if (!BaseInterface || !DerivedInterface) | |||
5629 | return false; | |||
5630 | ||||
5631 | if (Self.RequireCompleteType( | |||
5632 | KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5633 | return false; | |||
5634 | ||||
5635 | return BaseInterface->isSuperClassOf(DerivedInterface); | |||
5636 | } | |||
5637 | ||||
5638 | assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)(static_cast <bool> (Self.Context.hasSameUnqualifiedType (LhsT, RhsT) == (lhsRecord == rhsRecord)) ? void (0) : __assert_fail ("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)" , "clang/lib/Sema/SemaExprCXX.cpp", 5639, __extension__ __PRETTY_FUNCTION__ )) | |||
5639 | == (lhsRecord == rhsRecord))(static_cast <bool> (Self.Context.hasSameUnqualifiedType (LhsT, RhsT) == (lhsRecord == rhsRecord)) ? void (0) : __assert_fail ("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)" , "clang/lib/Sema/SemaExprCXX.cpp", 5639, __extension__ __PRETTY_FUNCTION__ )); | |||
5640 | ||||
5641 | // Unions are never base classes, and never have base classes. | |||
5642 | // It doesn't matter if they are complete or not. See PR#41843 | |||
5643 | if (lhsRecord && lhsRecord->getDecl()->isUnion()) | |||
5644 | return false; | |||
5645 | if (rhsRecord && rhsRecord->getDecl()->isUnion()) | |||
5646 | return false; | |||
5647 | ||||
5648 | if (lhsRecord == rhsRecord) | |||
5649 | return true; | |||
5650 | ||||
5651 | // C++0x [meta.rel]p2: | |||
5652 | // If Base and Derived are class types and are different types | |||
5653 | // (ignoring possible cv-qualifiers) then Derived shall be a | |||
5654 | // complete type. | |||
5655 | if (Self.RequireCompleteType(KeyLoc, RhsT, | |||
5656 | diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5657 | return false; | |||
5658 | ||||
5659 | return cast<CXXRecordDecl>(rhsRecord->getDecl()) | |||
5660 | ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); | |||
5661 | } | |||
5662 | case BTT_IsSame: | |||
5663 | return Self.Context.hasSameType(LhsT, RhsT); | |||
5664 | case BTT_TypeCompatible: { | |||
5665 | // GCC ignores cv-qualifiers on arrays for this builtin. | |||
5666 | Qualifiers LhsQuals, RhsQuals; | |||
5667 | QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals); | |||
5668 | QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals); | |||
5669 | return Self.Context.typesAreCompatible(Lhs, Rhs); | |||
5670 | } | |||
5671 | case BTT_IsConvertible: | |||
5672 | case BTT_IsConvertibleTo: { | |||
5673 | // C++0x [meta.rel]p4: | |||
5674 | // Given the following function prototype: | |||
5675 | // | |||
5676 | // template <class T> | |||
5677 | // typename add_rvalue_reference<T>::type create(); | |||
5678 | // | |||
5679 | // the predicate condition for a template specialization | |||
5680 | // is_convertible<From, To> shall be satisfied if and only if | |||
5681 | // the return expression in the following code would be | |||
5682 | // well-formed, including any implicit conversions to the return | |||
5683 | // type of the function: | |||
5684 | // | |||
5685 | // To test() { | |||
5686 | // return create<From>(); | |||
5687 | // } | |||
5688 | // | |||
5689 | // Access checking is performed as if in a context unrelated to To and | |||
5690 | // From. Only the validity of the immediate context of the expression | |||
5691 | // of the return-statement (including conversions to the return type) | |||
5692 | // is considered. | |||
5693 | // | |||
5694 | // We model the initialization as a copy-initialization of a temporary | |||
5695 | // of the appropriate type, which for this expression is identical to the | |||
5696 | // return statement (since NRVO doesn't apply). | |||
5697 | ||||
5698 | // Functions aren't allowed to return function or array types. | |||
5699 | if (RhsT->isFunctionType() || RhsT->isArrayType()) | |||
5700 | return false; | |||
5701 | ||||
5702 | // A return statement in a void function must have void type. | |||
5703 | if (RhsT->isVoidType()) | |||
5704 | return LhsT->isVoidType(); | |||
5705 | ||||
5706 | // A function definition requires a complete, non-abstract return type. | |||
5707 | if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT)) | |||
5708 | return false; | |||
5709 | ||||
5710 | // Compute the result of add_rvalue_reference. | |||
5711 | if (LhsT->isObjectType() || LhsT->isFunctionType()) | |||
5712 | LhsT = Self.Context.getRValueReferenceType(LhsT); | |||
5713 | ||||
5714 | // Build a fake source and destination for initialization. | |||
5715 | InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); | |||
5716 | OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), | |||
5717 | Expr::getValueKindForType(LhsT)); | |||
5718 | Expr *FromPtr = &From; | |||
5719 | InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, | |||
5720 | SourceLocation())); | |||
5721 | ||||
5722 | // Perform the initialization in an unevaluated context within a SFINAE | |||
5723 | // trap at translation unit scope. | |||
5724 | EnterExpressionEvaluationContext Unevaluated( | |||
5725 | Self, Sema::ExpressionEvaluationContext::Unevaluated); | |||
5726 | Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); | |||
5727 | Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); | |||
5728 | InitializationSequence Init(Self, To, Kind, FromPtr); | |||
5729 | if (Init.Failed()) | |||
5730 | return false; | |||
5731 | ||||
5732 | ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); | |||
5733 | return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); | |||
5734 | } | |||
5735 | ||||
5736 | case BTT_IsAssignable: | |||
5737 | case BTT_IsNothrowAssignable: | |||
5738 | case BTT_IsTriviallyAssignable: { | |||
5739 | // C++11 [meta.unary.prop]p3: | |||
5740 | // is_trivially_assignable is defined as: | |||
5741 | // is_assignable<T, U>::value is true and the assignment, as defined by | |||
5742 | // is_assignable, is known to call no operation that is not trivial | |||
5743 | // | |||
5744 | // is_assignable is defined as: | |||
5745 | // The expression declval<T>() = declval<U>() is well-formed when | |||
5746 | // treated as an unevaluated operand (Clause 5). | |||
5747 | // | |||
5748 | // For both, T and U shall be complete types, (possibly cv-qualified) | |||
5749 | // void, or arrays of unknown bound. | |||
5750 | if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && | |||
5751 | Self.RequireCompleteType(KeyLoc, LhsT, | |||
5752 | diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5753 | return false; | |||
5754 | if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && | |||
5755 | Self.RequireCompleteType(KeyLoc, RhsT, | |||
5756 | diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5757 | return false; | |||
5758 | ||||
5759 | // cv void is never assignable. | |||
5760 | if (LhsT->isVoidType() || RhsT->isVoidType()) | |||
5761 | return false; | |||
5762 | ||||
5763 | // Build expressions that emulate the effect of declval<T>() and | |||
5764 | // declval<U>(). | |||
5765 | if (LhsT->isObjectType() || LhsT->isFunctionType()) | |||
5766 | LhsT = Self.Context.getRValueReferenceType(LhsT); | |||
5767 | if (RhsT->isObjectType() || RhsT->isFunctionType()) | |||
5768 | RhsT = Self.Context.getRValueReferenceType(RhsT); | |||
5769 | OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), | |||
5770 | Expr::getValueKindForType(LhsT)); | |||
5771 | OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), | |||
5772 | Expr::getValueKindForType(RhsT)); | |||
5773 | ||||
5774 | // Attempt the assignment in an unevaluated context within a SFINAE | |||
5775 | // trap at translation unit scope. | |||
5776 | EnterExpressionEvaluationContext Unevaluated( | |||
5777 | Self, Sema::ExpressionEvaluationContext::Unevaluated); | |||
5778 | Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); | |||
5779 | Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); | |||
5780 | ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, | |||
5781 | &Rhs); | |||
5782 | if (Result.isInvalid()) | |||
5783 | return false; | |||
5784 | ||||
5785 | // Treat the assignment as unused for the purpose of -Wdeprecated-volatile. | |||
5786 | Self.CheckUnusedVolatileAssignment(Result.get()); | |||
5787 | ||||
5788 | if (SFINAE.hasErrorOccurred()) | |||
5789 | return false; | |||
5790 | ||||
5791 | if (BTT == BTT_IsAssignable) | |||
5792 | return true; | |||
5793 | ||||
5794 | if (BTT == BTT_IsNothrowAssignable) | |||
5795 | return Self.canThrow(Result.get()) == CT_Cannot; | |||
5796 | ||||
5797 | if (BTT == BTT_IsTriviallyAssignable) { | |||
5798 | // Under Objective-C ARC and Weak, if the destination has non-trivial | |||
5799 | // Objective-C lifetime, this is a non-trivial assignment. | |||
5800 | if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) | |||
5801 | return false; | |||
5802 | ||||
5803 | return !Result.get()->hasNonTrivialCall(Self.Context); | |||
5804 | } | |||
5805 | ||||
5806 | llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "clang/lib/Sema/SemaExprCXX.cpp" , 5806); | |||
5807 | return false; | |||
5808 | } | |||
5809 | default: llvm_unreachable("not a BTT")::llvm::llvm_unreachable_internal("not a BTT", "clang/lib/Sema/SemaExprCXX.cpp" , 5809); | |||
5810 | } | |||
5811 | llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented" , "clang/lib/Sema/SemaExprCXX.cpp", 5811); | |||
5812 | } | |||
5813 | ||||
5814 | ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, | |||
5815 | SourceLocation KWLoc, | |||
5816 | ParsedType Ty, | |||
5817 | Expr* DimExpr, | |||
5818 | SourceLocation RParen) { | |||
5819 | TypeSourceInfo *TSInfo; | |||
5820 | QualType T = GetTypeFromParser(Ty, &TSInfo); | |||
5821 | if (!TSInfo) | |||
5822 | TSInfo = Context.getTrivialTypeSourceInfo(T); | |||
5823 | ||||
5824 | return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); | |||
5825 | } | |||
5826 | ||||
5827 | static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, | |||
5828 | QualType T, Expr *DimExpr, | |||
5829 | SourceLocation KeyLoc) { | |||
5830 | assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")(static_cast <bool> (!T->isDependentType() && "Cannot evaluate traits of dependent type") ? void (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\"" , "clang/lib/Sema/SemaExprCXX.cpp", 5830, __extension__ __PRETTY_FUNCTION__ )); | |||
5831 | ||||
5832 | switch(ATT) { | |||
5833 | case ATT_ArrayRank: | |||
5834 | if (T->isArrayType()) { | |||
5835 | unsigned Dim = 0; | |||
5836 | while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { | |||
5837 | ++Dim; | |||
5838 | T = AT->getElementType(); | |||
5839 | } | |||
5840 | return Dim; | |||
5841 | } | |||
5842 | return 0; | |||
5843 | ||||
5844 | case ATT_ArrayExtent: { | |||
5845 | llvm::APSInt Value; | |||
5846 | uint64_t Dim; | |||
5847 | if (Self.VerifyIntegerConstantExpression( | |||
5848 | DimExpr, &Value, diag::err_dimension_expr_not_constant_integer) | |||
5849 | .isInvalid()) | |||
5850 | return 0; | |||
5851 | if (Value.isSigned() && Value.isNegative()) { | |||
5852 | Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) | |||
5853 | << DimExpr->getSourceRange(); | |||
5854 | return 0; | |||
5855 | } | |||
5856 | Dim = Value.getLimitedValue(); | |||
5857 | ||||
5858 | if (T->isArrayType()) { | |||
5859 | unsigned D = 0; | |||
5860 | bool Matched = false; | |||
5861 | while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { | |||
5862 | if (Dim == D) { | |||
5863 | Matched = true; | |||
5864 | break; | |||
5865 | } | |||
5866 | ++D; | |||
5867 | T = AT->getElementType(); | |||
5868 | } | |||
5869 | ||||
5870 | if (Matched && T->isArrayType()) { | |||
5871 | if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) | |||
5872 | return CAT->getSize().getLimitedValue(); | |||
5873 | } | |||
5874 | } | |||
5875 | return 0; | |||
5876 | } | |||
5877 | } | |||
5878 | llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented" , "clang/lib/Sema/SemaExprCXX.cpp", 5878); | |||
5879 | } | |||
5880 | ||||
5881 | ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, | |||
5882 | SourceLocation KWLoc, | |||
5883 | TypeSourceInfo *TSInfo, | |||
5884 | Expr* DimExpr, | |||
5885 | SourceLocation RParen) { | |||
5886 | QualType T = TSInfo->getType(); | |||
5887 | ||||
5888 | // FIXME: This should likely be tracked as an APInt to remove any host | |||
5889 | // assumptions about the width of size_t on the target. | |||
5890 | uint64_t Value = 0; | |||
5891 | if (!T->isDependentType()) | |||
5892 | Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); | |||
5893 | ||||
5894 | // While the specification for these traits from the Embarcadero C++ | |||
5895 | // compiler's documentation says the return type is 'unsigned int', Clang | |||
5896 | // returns 'size_t'. On Windows, the primary platform for the Embarcadero | |||
5897 | // compiler, there is no difference. On several other platforms this is an | |||
5898 | // important distinction. | |||
5899 | return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, | |||
5900 | RParen, Context.getSizeType()); | |||
5901 | } | |||
5902 | ||||
5903 | ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, | |||
5904 | SourceLocation KWLoc, | |||
5905 | Expr *Queried, | |||
5906 | SourceLocation RParen) { | |||
5907 | // If error parsing the expression, ignore. | |||
5908 | if (!Queried) | |||
5909 | return ExprError(); | |||
5910 | ||||
5911 | ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); | |||
5912 | ||||
5913 | return Result; | |||
5914 | } | |||
5915 | ||||
5916 | static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { | |||
5917 | switch (ET) { | |||
5918 | case ET_IsLValueExpr: return E->isLValue(); | |||
5919 | case ET_IsRValueExpr: | |||
5920 | return E->isPRValue(); | |||
5921 | } | |||
5922 | llvm_unreachable("Expression trait not covered by switch")::llvm::llvm_unreachable_internal("Expression trait not covered by switch" , "clang/lib/Sema/SemaExprCXX.cpp", 5922); | |||
5923 | } | |||
5924 | ||||
5925 | ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, | |||
5926 | SourceLocation KWLoc, | |||
5927 | Expr *Queried, | |||
5928 | SourceLocation RParen) { | |||
5929 | if (Queried->isTypeDependent()) { | |||
5930 | // Delay type-checking for type-dependent expressions. | |||
5931 | } else if (Queried->hasPlaceholderType()) { | |||
5932 | ExprResult PE = CheckPlaceholderExpr(Queried); | |||
5933 | if (PE.isInvalid()) return ExprError(); | |||
5934 | return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen); | |||
5935 | } | |||
5936 | ||||
5937 | bool Value = EvaluateExpressionTrait(ET, Queried); | |||
5938 | ||||
5939 | return new (Context) | |||
5940 | ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); | |||
5941 | } | |||
5942 | ||||
5943 | QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, | |||
5944 | ExprValueKind &VK, | |||
5945 | SourceLocation Loc, | |||
5946 | bool isIndirect) { | |||
5947 | assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&(static_cast <bool> (!LHS.get()->hasPlaceholderType( ) && !RHS.get()->hasPlaceholderType() && "placeholders should have been weeded out by now" ) ? void (0) : __assert_fail ("!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() && \"placeholders should have been weeded out by now\"" , "clang/lib/Sema/SemaExprCXX.cpp", 5948, __extension__ __PRETTY_FUNCTION__ )) | |||
5948 | "placeholders should have been weeded out by now")(static_cast <bool> (!LHS.get()->hasPlaceholderType( ) && !RHS.get()->hasPlaceholderType() && "placeholders should have been weeded out by now" ) ? void (0) : __assert_fail ("!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() && \"placeholders should have been weeded out by now\"" , "clang/lib/Sema/SemaExprCXX.cpp", 5948, __extension__ __PRETTY_FUNCTION__ )); | |||
5949 | ||||
5950 | // The LHS undergoes lvalue conversions if this is ->*, and undergoes the | |||
5951 | // temporary materialization conversion otherwise. | |||
5952 | if (isIndirect) | |||
5953 | LHS = DefaultLvalueConversion(LHS.get()); | |||
5954 | else if (LHS.get()->isPRValue()) | |||
5955 | LHS = TemporaryMaterializationConversion(LHS.get()); | |||
5956 | if (LHS.isInvalid()) | |||
5957 | return QualType(); | |||
5958 | ||||
5959 | // The RHS always undergoes lvalue conversions. | |||
5960 | RHS = DefaultLvalueConversion(RHS.get()); | |||
5961 | if (RHS.isInvalid()) return QualType(); | |||
5962 | ||||
5963 | const char *OpSpelling = isIndirect ? "->*" : ".*"; | |||
5964 | // C++ 5.5p2 | |||
5965 | // The binary operator .* [p3: ->*] binds its second operand, which shall | |||
5966 | // be of type "pointer to member of T" (where T is a completely-defined | |||
5967 | // class type) [...] | |||
5968 | QualType RHSType = RHS.get()->getType(); | |||
5969 | const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); | |||
5970 | if (!MemPtr) { | |||
5971 | Diag(Loc, diag::err_bad_memptr_rhs) | |||
5972 | << OpSpelling << RHSType << RHS.get()->getSourceRange(); | |||
5973 | return QualType(); | |||
5974 | } | |||
5975 | ||||
5976 | QualType Class(MemPtr->getClass(), 0); | |||
5977 | ||||
5978 | // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the | |||
5979 | // member pointer points must be completely-defined. However, there is no | |||
5980 | // reason for this semantic distinction, and the rule is not enforced by | |||
5981 | // other compilers. Therefore, we do not check this property, as it is | |||
5982 | // likely to be considered a defect. | |||
5983 | ||||
5984 | // C++ 5.5p2 | |||
5985 | // [...] to its first operand, which shall be of class T or of a class of | |||
5986 | // which T is an unambiguous and accessible base class. [p3: a pointer to | |||
5987 | // such a class] | |||
5988 | QualType LHSType = LHS.get()->getType(); | |||
5989 | if (isIndirect) { | |||
5990 | if (const PointerType *Ptr = LHSType->getAs<PointerType>()) | |||
5991 | LHSType = Ptr->getPointeeType(); | |||
5992 | else { | |||
5993 | Diag(Loc, diag::err_bad_memptr_lhs) | |||
5994 | << OpSpelling << 1 << LHSType | |||
5995 | << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); | |||
5996 | return QualType(); | |||
5997 | } | |||
5998 | } | |||
5999 | ||||
6000 | if (!Context.hasSameUnqualifiedType(Class, LHSType)) { | |||
6001 | // If we want to check the hierarchy, we need a complete type. | |||
6002 | if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, | |||
6003 | OpSpelling, (int)isIndirect)) { | |||
6004 | return QualType(); | |||
6005 | } | |||
6006 | ||||
6007 | if (!IsDerivedFrom(Loc, LHSType, Class)) { | |||
6008 | Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling | |||
6009 | << (int)isIndirect << LHS.get()->getType(); | |||
6010 | return QualType(); | |||
6011 | } | |||
6012 | ||||
6013 | CXXCastPath BasePath; | |||
6014 | if (CheckDerivedToBaseConversion( | |||
6015 | LHSType, Class, Loc, | |||
6016 | SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), | |||
6017 | &BasePath)) | |||
6018 | return QualType(); | |||
6019 | ||||
6020 | // Cast LHS to type of use. | |||
6021 | QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers()); | |||
6022 | if (isIndirect) | |||
6023 | UseType = Context.getPointerType(UseType); | |||
6024 | ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind(); | |||
6025 | LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, | |||
6026 | &BasePath); | |||
6027 | } | |||
6028 | ||||
6029 | if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { | |||
6030 | // Diagnose use of pointer-to-member type which when used as | |||
6031 | // the functional cast in a pointer-to-member expression. | |||
6032 | Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; | |||
6033 | return QualType(); | |||
6034 | } | |||
6035 | ||||
6036 | // C++ 5.5p2 | |||
6037 | // The result is an object or a function of the type specified by the | |||
6038 | // second operand. | |||
6039 | // The cv qualifiers are the union of those in the pointer and the left side, | |||
6040 | // in accordance with 5.5p5 and 5.2.5. | |||
6041 | QualType Result = MemPtr->getPointeeType(); | |||
6042 | Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); | |||
6043 | ||||
6044 | // C++0x [expr.mptr.oper]p6: | |||
6045 | // In a .* expression whose object expression is an rvalue, the program is | |||
6046 | // ill-formed if the second operand is a pointer to member function with | |||
6047 | // ref-qualifier &. In a ->* expression or in a .* expression whose object | |||
6048 | // expression is an lvalue, the program is ill-formed if the second operand | |||
6049 | // is a pointer to member function with ref-qualifier &&. | |||
6050 | if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { | |||
6051 | switch (Proto->getRefQualifier()) { | |||
6052 | case RQ_None: | |||
6053 | // Do nothing | |||
6054 | break; | |||
6055 | ||||
6056 | case RQ_LValue: | |||
6057 | if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) { | |||
6058 | // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq | |||
6059 | // is (exactly) 'const'. | |||
6060 | if (Proto->isConst() && !Proto->isVolatile()) | |||
6061 | Diag(Loc, getLangOpts().CPlusPlus20 | |||
6062 | ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue | |||
6063 | : diag::ext_pointer_to_const_ref_member_on_rvalue); | |||
6064 | else | |||
6065 | Diag(Loc, diag::err_pointer_to_member_oper_value_classify) | |||
6066 | << RHSType << 1 << LHS.get()->getSourceRange(); | |||
6067 | } | |||
6068 | break; | |||
6069 | ||||
6070 | case RQ_RValue: | |||
6071 | if (isIndirect || !LHS.get()->Classify(Context).isRValue()) | |||
6072 | Diag(Loc, diag::err_pointer_to_member_oper_value_classify) | |||
6073 | << RHSType << 0 << LHS.get()->getSourceRange(); | |||
6074 | break; | |||
6075 | } | |||
6076 | } | |||
6077 | ||||
6078 | // C++ [expr.mptr.oper]p6: | |||
6079 | // The result of a .* expression whose second operand is a pointer | |||
6080 | // to a data member is of the same value category as its | |||
6081 | // first operand. The result of a .* expression whose second | |||
6082 | // operand is a pointer to a member function is a prvalue. The | |||
6083 | // result of an ->* expression is an lvalue if its second operand | |||
6084 | // is a pointer to data member and a prvalue otherwise. | |||
6085 | if (Result->isFunctionType()) { | |||
6086 | VK = VK_PRValue; | |||
6087 | return Context.BoundMemberTy; | |||
6088 | } else if (isIndirect) { | |||
6089 | VK = VK_LValue; | |||
6090 | } else { | |||
6091 | VK = LHS.get()->getValueKind(); | |||
6092 | } | |||
6093 | ||||
6094 | return Result; | |||
6095 | } | |||
6096 | ||||
6097 | /// Try to convert a type to another according to C++11 5.16p3. | |||
6098 | /// | |||
6099 | /// This is part of the parameter validation for the ? operator. If either | |||
6100 | /// value operand is a class type, the two operands are attempted to be | |||
6101 | /// converted to each other. This function does the conversion in one direction. | |||
6102 | /// It returns true if the program is ill-formed and has already been diagnosed | |||
6103 | /// as such. | |||
6104 | static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, | |||
6105 | SourceLocation QuestionLoc, | |||
6106 | bool &HaveConversion, | |||
6107 | QualType &ToType) { | |||
6108 | HaveConversion = false; | |||
6109 | ToType = To->getType(); | |||
6110 | ||||
6111 | InitializationKind Kind = | |||
6112 | InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation()); | |||
6113 | // C++11 5.16p3 | |||
6114 | // The process for determining whether an operand expression E1 of type T1 | |||
6115 | // can be converted to match an operand expression E2 of type T2 is defined | |||
6116 | // as follows: | |||
6117 | // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be | |||
6118 | // implicitly converted to type "lvalue reference to T2", subject to the | |||
6119 | // constraint that in the conversion the reference must bind directly to | |||
6120 | // an lvalue. | |||
6121 | // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be | |||
6122 | // implicitly converted to the type "rvalue reference to R2", subject to | |||
6123 | // the constraint that the reference must bind directly. | |||
6124 | if (To->isGLValue()) { | |||
6125 | QualType T = Self.Context.getReferenceQualifiedType(To); | |||
6126 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); | |||
6127 | ||||
6128 | InitializationSequence InitSeq(Self, Entity, Kind, From); | |||
6129 | if (InitSeq.isDirectReferenceBinding()) { | |||
6130 | ToType = T; | |||
6131 | HaveConversion = true; | |||
6132 | return false; | |||
6133 | } | |||
6134 | ||||
6135 | if (InitSeq.isAmbiguous()) | |||
6136 | return InitSeq.Diagnose(Self, Entity, Kind, From); | |||
6137 | } | |||
6138 | ||||
6139 | // -- If E2 is an rvalue, or if the conversion above cannot be done: | |||
6140 | // -- if E1 and E2 have class type, and the underlying class types are | |||
6141 | // the same or one is a base class of the other: | |||
6142 | QualType FTy = From->getType(); | |||
6143 | QualType TTy = To->getType(); | |||
6144 | const RecordType *FRec = FTy->getAs<RecordType>(); | |||
6145 | const RecordType *TRec = TTy->getAs<RecordType>(); | |||
6146 | bool FDerivedFromT = FRec && TRec && FRec != TRec && | |||
6147 | Self.IsDerivedFrom(QuestionLoc, FTy, TTy); | |||
6148 | if (FRec && TRec && (FRec == TRec || FDerivedFromT || | |||
6149 | Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) { | |||
6150 | // E1 can be converted to match E2 if the class of T2 is the | |||
6151 | // same type as, or a base class of, the class of T1, and | |||
6152 | // [cv2 > cv1]. | |||
6153 | if (FRec == TRec || FDerivedFromT) { | |||
6154 | if (TTy.isAtLeastAsQualifiedAs(FTy)) { | |||
6155 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); | |||
6156 | InitializationSequence InitSeq(Self, Entity, Kind, From); | |||
6157 | if (InitSeq) { | |||
6158 | HaveConversion = true; | |||
6159 | return false; | |||
6160 | } | |||
6161 | ||||
6162 | if (InitSeq.isAmbiguous()) | |||
6163 | return InitSeq.Diagnose(Self, Entity, Kind, From); | |||
6164 | } | |||
6165 | } | |||
6166 | ||||
6167 | return false; | |||
6168 | } | |||
6169 | ||||
6170 | // -- Otherwise: E1 can be converted to match E2 if E1 can be | |||
6171 | // implicitly converted to the type that expression E2 would have | |||
6172 | // if E2 were converted to an rvalue (or the type it has, if E2 is | |||
6173 | // an rvalue). | |||
6174 | // | |||
6175 | // This actually refers very narrowly to the lvalue-to-rvalue conversion, not | |||
6176 | // to the array-to-pointer or function-to-pointer conversions. | |||
6177 | TTy = TTy.getNonLValueExprType(Self.Context); | |||
6178 | ||||
6179 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); | |||
6180 | InitializationSequence InitSeq(Self, Entity, Kind, From); | |||
6181 | HaveConversion = !InitSeq.Failed(); | |||
6182 | ToType = TTy; | |||
6183 | if (InitSeq.isAmbiguous()) | |||
6184 | return InitSeq.Diagnose(Self, Entity, Kind, From); | |||
6185 | ||||
6186 | return false; | |||
6187 | } | |||
6188 | ||||
6189 | /// Try to find a common type for two according to C++0x 5.16p5. | |||
6190 | /// | |||
6191 | /// This is part of the parameter validation for the ? operator. If either | |||
6192 | /// value operand is a class type, overload resolution is used to find a | |||
6193 | /// conversion to a common type. | |||
6194 | static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, | |||
6195 | SourceLocation QuestionLoc) { | |||
6196 | Expr *Args[2] = { LHS.get(), RHS.get() }; | |||
6197 | OverloadCandidateSet CandidateSet(QuestionLoc, | |||
6198 | OverloadCandidateSet::CSK_Operator); | |||
6199 | Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, | |||
6200 | CandidateSet); | |||
6201 | ||||
6202 | OverloadCandidateSet::iterator Best; | |||
6203 | switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { | |||
6204 | case OR_Success: { | |||
6205 | // We found a match. Perform the conversions on the arguments and move on. | |||
6206 | ExprResult LHSRes = Self.PerformImplicitConversion( | |||
6207 | LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], | |||
6208 | Sema::AA_Converting); | |||
6209 | if (LHSRes.isInvalid()) | |||
6210 | break; | |||
6211 | LHS = LHSRes; | |||
6212 | ||||
6213 | ExprResult RHSRes = Self.PerformImplicitConversion( | |||
6214 | RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], | |||
6215 | Sema::AA_Converting); | |||
6216 | if (RHSRes.isInvalid()) | |||
6217 | break; | |||
6218 | RHS = RHSRes; | |||
6219 | if (Best->Function) | |||
6220 | Self.MarkFunctionReferenced(QuestionLoc, Best->Function); | |||
6221 | return false; | |||
6222 | } | |||
6223 | ||||
6224 | case OR_No_Viable_Function: | |||
6225 | ||||
6226 | // Emit a better diagnostic if one of the expressions is a null pointer | |||
6227 | // constant and the other is a pointer type. In this case, the user most | |||
6228 | // likely forgot to take the address of the other expression. | |||
6229 | if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | |||
6230 | return true; | |||
6231 | ||||
6232 | Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | |||
6233 | << LHS.get()->getType() << RHS.get()->getType() | |||
6234 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6235 | return true; | |||
6236 | ||||
6237 | case OR_Ambiguous: | |||
6238 | Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) | |||
6239 | << LHS.get()->getType() << RHS.get()->getType() | |||
6240 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6241 | // FIXME: Print the possible common types by printing the return types of | |||
6242 | // the viable candidates. | |||
6243 | break; | |||
6244 | ||||
6245 | case OR_Deleted: | |||
6246 | llvm_unreachable("Conditional operator has only built-in overloads")::llvm::llvm_unreachable_internal("Conditional operator has only built-in overloads" , "clang/lib/Sema/SemaExprCXX.cpp", 6246); | |||
6247 | } | |||
6248 | return true; | |||
6249 | } | |||
6250 | ||||
6251 | /// Perform an "extended" implicit conversion as returned by | |||
6252 | /// TryClassUnification. | |||
6253 | static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { | |||
6254 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); | |||
6255 | InitializationKind Kind = | |||
6256 | InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation()); | |||
6257 | Expr *Arg = E.get(); | |||
6258 | InitializationSequence InitSeq(Self, Entity, Kind, Arg); | |||
6259 | ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); | |||
6260 | if (Result.isInvalid()) | |||
6261 | return true; | |||
6262 | ||||
6263 | E = Result; | |||
6264 | return false; | |||
6265 | } | |||
6266 | ||||
6267 | // Check the condition operand of ?: to see if it is valid for the GCC | |||
6268 | // extension. | |||
6269 | static bool isValidVectorForConditionalCondition(ASTContext &Ctx, | |||
6270 | QualType CondTy) { | |||
6271 | if (!CondTy->isVectorType() && !CondTy->isExtVectorType()) | |||
6272 | return false; | |||
6273 | const QualType EltTy = | |||
6274 | cast<VectorType>(CondTy.getCanonicalType())->getElementType(); | |||
6275 | assert(!EltTy->isEnumeralType() && "Vectors cant be enum types")(static_cast <bool> (!EltTy->isEnumeralType() && "Vectors cant be enum types") ? void (0) : __assert_fail ("!EltTy->isEnumeralType() && \"Vectors cant be enum types\"" , "clang/lib/Sema/SemaExprCXX.cpp", 6275, __extension__ __PRETTY_FUNCTION__ )); | |||
6276 | return EltTy->isIntegralType(Ctx); | |||
6277 | } | |||
6278 | ||||
6279 | static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx, | |||
6280 | QualType CondTy) { | |||
6281 | if (!CondTy->isVLSTBuiltinType()) | |||
6282 | return false; | |||
6283 | const QualType EltTy = | |||
6284 | cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx); | |||
6285 | assert(!EltTy->isEnumeralType() && "Vectors cant be enum types")(static_cast <bool> (!EltTy->isEnumeralType() && "Vectors cant be enum types") ? void (0) : __assert_fail ("!EltTy->isEnumeralType() && \"Vectors cant be enum types\"" , "clang/lib/Sema/SemaExprCXX.cpp", 6285, __extension__ __PRETTY_FUNCTION__ )); | |||
6286 | return EltTy->isIntegralType(Ctx); | |||
6287 | } | |||
6288 | ||||
6289 | QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, | |||
6290 | ExprResult &RHS, | |||
6291 | SourceLocation QuestionLoc) { | |||
6292 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
6293 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
6294 | ||||
6295 | QualType CondType = Cond.get()->getType(); | |||
6296 | const auto *CondVT = CondType->castAs<VectorType>(); | |||
6297 | QualType CondElementTy = CondVT->getElementType(); | |||
6298 | unsigned CondElementCount = CondVT->getNumElements(); | |||
6299 | QualType LHSType = LHS.get()->getType(); | |||
6300 | const auto *LHSVT = LHSType->getAs<VectorType>(); | |||
6301 | QualType RHSType = RHS.get()->getType(); | |||
6302 | const auto *RHSVT = RHSType->getAs<VectorType>(); | |||
6303 | ||||
6304 | QualType ResultType; | |||
6305 | ||||
6306 | ||||
6307 | if (LHSVT && RHSVT) { | |||
6308 | if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) { | |||
6309 | Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch) | |||
6310 | << /*isExtVector*/ isa<ExtVectorType>(CondVT); | |||
6311 | return {}; | |||
6312 | } | |||
6313 | ||||
6314 | // If both are vector types, they must be the same type. | |||
6315 | if (!Context.hasSameType(LHSType, RHSType)) { | |||
6316 | Diag(QuestionLoc, diag::err_conditional_vector_mismatched) | |||
6317 | << LHSType << RHSType; | |||
6318 | return {}; | |||
6319 | } | |||
6320 | ResultType = Context.getCommonSugaredType(LHSType, RHSType); | |||
6321 | } else if (LHSVT || RHSVT) { | |||
6322 | ResultType = CheckVectorOperands( | |||
6323 | LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true, | |||
6324 | /*AllowBoolConversions*/ false, | |||
6325 | /*AllowBoolOperation*/ true, | |||
6326 | /*ReportInvalid*/ true); | |||
6327 | if (ResultType.isNull()) | |||
6328 | return {}; | |||
6329 | } else { | |||
6330 | // Both are scalar. | |||
6331 | LHSType = LHSType.getUnqualifiedType(); | |||
6332 | RHSType = RHSType.getUnqualifiedType(); | |||
6333 | QualType ResultElementTy = | |||
6334 | Context.hasSameType(LHSType, RHSType) | |||
6335 | ? Context.getCommonSugaredType(LHSType, RHSType) | |||
6336 | : UsualArithmeticConversions(LHS, RHS, QuestionLoc, | |||
6337 | ACK_Conditional); | |||
6338 | ||||
6339 | if (ResultElementTy->isEnumeralType()) { | |||
6340 | Diag(QuestionLoc, diag::err_conditional_vector_operand_type) | |||
6341 | << ResultElementTy; | |||
6342 | return {}; | |||
6343 | } | |||
6344 | if (CondType->isExtVectorType()) | |||
6345 | ResultType = | |||
6346 | Context.getExtVectorType(ResultElementTy, CondVT->getNumElements()); | |||
6347 | else | |||
6348 | ResultType = Context.getVectorType( | |||
6349 | ResultElementTy, CondVT->getNumElements(), VectorType::GenericVector); | |||
6350 | ||||
6351 | LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat); | |||
6352 | RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat); | |||
6353 | } | |||
6354 | ||||
6355 | assert(!ResultType.isNull() && ResultType->isVectorType() &&(static_cast <bool> (!ResultType.isNull() && ResultType ->isVectorType() && (!CondType->isExtVectorType () || ResultType->isExtVectorType()) && "Result should have been a vector type" ) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVectorType() && (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && \"Result should have been a vector type\"" , "clang/lib/Sema/SemaExprCXX.cpp", 6357, __extension__ __PRETTY_FUNCTION__ )) | |||
6356 | (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&(static_cast <bool> (!ResultType.isNull() && ResultType ->isVectorType() && (!CondType->isExtVectorType () || ResultType->isExtVectorType()) && "Result should have been a vector type" ) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVectorType() && (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && \"Result should have been a vector type\"" , "clang/lib/Sema/SemaExprCXX.cpp", 6357, __extension__ __PRETTY_FUNCTION__ )) | |||
6357 | "Result should have been a vector type")(static_cast <bool> (!ResultType.isNull() && ResultType ->isVectorType() && (!CondType->isExtVectorType () || ResultType->isExtVectorType()) && "Result should have been a vector type" ) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVectorType() && (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && \"Result should have been a vector type\"" , "clang/lib/Sema/SemaExprCXX.cpp", 6357, __extension__ __PRETTY_FUNCTION__ )); | |||
6358 | auto *ResultVectorTy = ResultType->castAs<VectorType>(); | |||
6359 | QualType ResultElementTy = ResultVectorTy->getElementType(); | |||
6360 | unsigned ResultElementCount = ResultVectorTy->getNumElements(); | |||
6361 | ||||
6362 | if (ResultElementCount != CondElementCount) { | |||
6363 | Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType | |||
6364 | << ResultType; | |||
6365 | return {}; | |||
6366 | } | |||
6367 | ||||
6368 | if (Context.getTypeSize(ResultElementTy) != | |||
6369 | Context.getTypeSize(CondElementTy)) { | |||
6370 | Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType | |||
6371 | << ResultType; | |||
6372 | return {}; | |||
6373 | } | |||
6374 | ||||
6375 | return ResultType; | |||
6376 | } | |||
6377 | ||||
6378 | QualType Sema::CheckSizelessVectorConditionalTypes(ExprResult &Cond, | |||
6379 | ExprResult &LHS, | |||
6380 | ExprResult &RHS, | |||
6381 | SourceLocation QuestionLoc) { | |||
6382 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
6383 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
6384 | ||||
6385 | QualType CondType = Cond.get()->getType(); | |||
6386 | const auto *CondBT = CondType->castAs<BuiltinType>(); | |||
6387 | QualType CondElementTy = CondBT->getSveEltType(Context); | |||
6388 | llvm::ElementCount CondElementCount = | |||
6389 | Context.getBuiltinVectorTypeInfo(CondBT).EC; | |||
6390 | ||||
6391 | QualType LHSType = LHS.get()->getType(); | |||
6392 | const auto *LHSBT = | |||
6393 | LHSType->isVLSTBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr; | |||
6394 | QualType RHSType = RHS.get()->getType(); | |||
6395 | const auto *RHSBT = | |||
6396 | RHSType->isVLSTBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr; | |||
6397 | ||||
6398 | QualType ResultType; | |||
6399 | ||||
6400 | if (LHSBT && RHSBT) { | |||
6401 | // If both are sizeless vector types, they must be the same type. | |||
6402 | if (!Context.hasSameType(LHSType, RHSType)) { | |||
6403 | Diag(QuestionLoc, diag::err_conditional_vector_mismatched) | |||
6404 | << LHSType << RHSType; | |||
6405 | return QualType(); | |||
6406 | } | |||
6407 | ResultType = LHSType; | |||
6408 | } else if (LHSBT || RHSBT) { | |||
6409 | ResultType = CheckSizelessVectorOperands( | |||
6410 | LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional); | |||
6411 | if (ResultType.isNull()) | |||
6412 | return QualType(); | |||
6413 | } else { | |||
6414 | // Both are scalar so splat | |||
6415 | QualType ResultElementTy; | |||
6416 | LHSType = LHSType.getCanonicalType().getUnqualifiedType(); | |||
6417 | RHSType = RHSType.getCanonicalType().getUnqualifiedType(); | |||
6418 | ||||
6419 | if (Context.hasSameType(LHSType, RHSType)) | |||
6420 | ResultElementTy = LHSType; | |||
6421 | else | |||
6422 | ResultElementTy = | |||
6423 | UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); | |||
6424 | ||||
6425 | if (ResultElementTy->isEnumeralType()) { | |||
6426 | Diag(QuestionLoc, diag::err_conditional_vector_operand_type) | |||
6427 | << ResultElementTy; | |||
6428 | return QualType(); | |||
6429 | } | |||
6430 | ||||
6431 | ResultType = Context.getScalableVectorType( | |||
6432 | ResultElementTy, CondElementCount.getKnownMinValue()); | |||
6433 | ||||
6434 | LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat); | |||
6435 | RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat); | |||
6436 | } | |||
6437 | ||||
6438 | assert(!ResultType.isNull() && ResultType->isVLSTBuiltinType() &&(static_cast <bool> (!ResultType.isNull() && ResultType ->isVLSTBuiltinType() && "Result should have been a vector type" ) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVLSTBuiltinType() && \"Result should have been a vector type\"" , "clang/lib/Sema/SemaExprCXX.cpp", 6439, __extension__ __PRETTY_FUNCTION__ )) | |||
6439 | "Result should have been a vector type")(static_cast <bool> (!ResultType.isNull() && ResultType ->isVLSTBuiltinType() && "Result should have been a vector type" ) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVLSTBuiltinType() && \"Result should have been a vector type\"" , "clang/lib/Sema/SemaExprCXX.cpp", 6439, __extension__ __PRETTY_FUNCTION__ )); | |||
6440 | auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>(); | |||
6441 | QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context); | |||
6442 | llvm::ElementCount ResultElementCount = | |||
6443 | Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC; | |||
6444 | ||||
6445 | if (ResultElementCount != CondElementCount) { | |||
6446 | Diag(QuestionLoc, diag::err_conditional_vector_size) | |||
6447 | << CondType << ResultType; | |||
6448 | return QualType(); | |||
6449 | } | |||
6450 | ||||
6451 | if (Context.getTypeSize(ResultElementTy) != | |||
6452 | Context.getTypeSize(CondElementTy)) { | |||
6453 | Diag(QuestionLoc, diag::err_conditional_vector_element_size) | |||
6454 | << CondType << ResultType; | |||
6455 | return QualType(); | |||
6456 | } | |||
6457 | ||||
6458 | return ResultType; | |||
6459 | } | |||
6460 | ||||
6461 | /// Check the operands of ?: under C++ semantics. | |||
6462 | /// | |||
6463 | /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y | |||
6464 | /// extension. In this case, LHS == Cond. (But they're not aliases.) | |||
6465 | /// | |||
6466 | /// This function also implements GCC's vector extension and the | |||
6467 | /// OpenCL/ext_vector_type extension for conditionals. The vector extensions | |||
6468 | /// permit the use of a?b:c where the type of a is that of a integer vector with | |||
6469 | /// the same number of elements and size as the vectors of b and c. If one of | |||
6470 | /// either b or c is a scalar it is implicitly converted to match the type of | |||
6471 | /// the vector. Otherwise the expression is ill-formed. If both b and c are | |||
6472 | /// scalars, then b and c are checked and converted to the type of a if | |||
6473 | /// possible. | |||
6474 | /// | |||
6475 | /// The expressions are evaluated differently for GCC's and OpenCL's extensions. | |||
6476 | /// For the GCC extension, the ?: operator is evaluated as | |||
6477 | /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]). | |||
6478 | /// For the OpenCL extensions, the ?: operator is evaluated as | |||
6479 | /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. , | |||
6480 | /// most-significant-bit-set(a[n]) ? b[n] : c[n]). | |||
6481 | QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, | |||
6482 | ExprResult &RHS, ExprValueKind &VK, | |||
6483 | ExprObjectKind &OK, | |||
6484 | SourceLocation QuestionLoc) { | |||
6485 | // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface | |||
6486 | // pointers. | |||
6487 | ||||
6488 | // Assume r-value. | |||
6489 | VK = VK_PRValue; | |||
6490 | OK = OK_Ordinary; | |||
6491 | bool IsVectorConditional = | |||
6492 | isValidVectorForConditionalCondition(Context, Cond.get()->getType()); | |||
6493 | ||||
6494 | bool IsSizelessVectorConditional = | |||
6495 | isValidSizelessVectorForConditionalCondition(Context, | |||
6496 | Cond.get()->getType()); | |||
6497 | ||||
6498 | // C++11 [expr.cond]p1 | |||
6499 | // The first expression is contextually converted to bool. | |||
6500 | if (!Cond.get()->isTypeDependent()) { | |||
6501 | ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional | |||
6502 | ? DefaultFunctionArrayLvalueConversion(Cond.get()) | |||
6503 | : CheckCXXBooleanCondition(Cond.get()); | |||
6504 | if (CondRes.isInvalid()) | |||
6505 | return QualType(); | |||
6506 | Cond = CondRes; | |||
6507 | } else { | |||
6508 | // To implement C++, the first expression typically doesn't alter the result | |||
6509 | // type of the conditional, however the GCC compatible vector extension | |||
6510 | // changes the result type to be that of the conditional. Since we cannot | |||
6511 | // know if this is a vector extension here, delay the conversion of the | |||
6512 | // LHS/RHS below until later. | |||
6513 | return Context.DependentTy; | |||
6514 | } | |||
6515 | ||||
6516 | ||||
6517 | // Either of the arguments dependent? | |||
6518 | if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) | |||
6519 | return Context.DependentTy; | |||
6520 | ||||
6521 | // C++11 [expr.cond]p2 | |||
6522 | // If either the second or the third operand has type (cv) void, ... | |||
6523 | QualType LTy = LHS.get()->getType(); | |||
6524 | QualType RTy = RHS.get()->getType(); | |||
6525 | bool LVoid = LTy->isVoidType(); | |||
6526 | bool RVoid = RTy->isVoidType(); | |||
6527 | if (LVoid || RVoid) { | |||
6528 | // ... one of the following shall hold: | |||
6529 | // -- The second or the third operand (but not both) is a (possibly | |||
6530 | // parenthesized) throw-expression; the result is of the type | |||
6531 | // and value category of the other. | |||
6532 | bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts()); | |||
6533 | bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts()); | |||
6534 | ||||
6535 | // Void expressions aren't legal in the vector-conditional expressions. | |||
6536 | if (IsVectorConditional) { | |||
6537 | SourceRange DiagLoc = | |||
6538 | LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange(); | |||
6539 | bool IsThrow = LVoid ? LThrow : RThrow; | |||
6540 | Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void) | |||
6541 | << DiagLoc << IsThrow; | |||
6542 | return QualType(); | |||
6543 | } | |||
6544 | ||||
6545 | if (LThrow != RThrow) { | |||
6546 | Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); | |||
6547 | VK = NonThrow->getValueKind(); | |||
6548 | // DR (no number yet): the result is a bit-field if the | |||
6549 | // non-throw-expression operand is a bit-field. | |||
6550 | OK = NonThrow->getObjectKind(); | |||
6551 | return NonThrow->getType(); | |||
6552 | } | |||
6553 | ||||
6554 | // -- Both the second and third operands have type void; the result is of | |||
6555 | // type void and is a prvalue. | |||
6556 | if (LVoid && RVoid) | |||
6557 | return Context.getCommonSugaredType(LTy, RTy); | |||
6558 | ||||
6559 | // Neither holds, error. | |||
6560 | Diag(QuestionLoc, diag::err_conditional_void_nonvoid) | |||
6561 | << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) | |||
6562 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6563 | return QualType(); | |||
6564 | } | |||
6565 | ||||
6566 | // Neither is void. | |||
6567 | if (IsVectorConditional) | |||
6568 | return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); | |||
6569 | ||||
6570 | if (IsSizelessVectorConditional) | |||
6571 | return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); | |||
6572 | ||||
6573 | // C++11 [expr.cond]p3 | |||
6574 | // Otherwise, if the second and third operand have different types, and | |||
6575 | // either has (cv) class type [...] an attempt is made to convert each of | |||
6576 | // those operands to the type of the other. | |||
6577 | if (!Context.hasSameType(LTy, RTy) && | |||
6578 | (LTy->isRecordType() || RTy->isRecordType())) { | |||
6579 | // These return true if a single direction is already ambiguous. | |||
6580 | QualType L2RType, R2LType; | |||
6581 | bool HaveL2R, HaveR2L; | |||
6582 | if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) | |||
6583 | return QualType(); | |||
6584 | if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) | |||
6585 | return QualType(); | |||
6586 | ||||
6587 | // If both can be converted, [...] the program is ill-formed. | |||
6588 | if (HaveL2R && HaveR2L) { | |||
6589 | Diag(QuestionLoc, diag::err_conditional_ambiguous) | |||
6590 | << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6591 | return QualType(); | |||
6592 | } | |||
6593 | ||||
6594 | // If exactly one conversion is possible, that conversion is applied to | |||
6595 | // the chosen operand and the converted operands are used in place of the | |||
6596 | // original operands for the remainder of this section. | |||
6597 | if (HaveL2R) { | |||
6598 | if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) | |||
6599 | return QualType(); | |||
6600 | LTy = LHS.get()->getType(); | |||
6601 | } else if (HaveR2L) { | |||
6602 | if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) | |||
6603 | return QualType(); | |||
6604 | RTy = RHS.get()->getType(); | |||
6605 | } | |||
6606 | } | |||
6607 | ||||
6608 | // C++11 [expr.cond]p3 | |||
6609 | // if both are glvalues of the same value category and the same type except | |||
6610 | // for cv-qualification, an attempt is made to convert each of those | |||
6611 | // operands to the type of the other. | |||
6612 | // FIXME: | |||
6613 | // Resolving a defect in P0012R1: we extend this to cover all cases where | |||
6614 | // one of the operands is reference-compatible with the other, in order | |||
6615 | // to support conditionals between functions differing in noexcept. This | |||
6616 | // will similarly cover difference in array bounds after P0388R4. | |||
6617 | // FIXME: If LTy and RTy have a composite pointer type, should we convert to | |||
6618 | // that instead? | |||
6619 | ExprValueKind LVK = LHS.get()->getValueKind(); | |||
6620 | ExprValueKind RVK = RHS.get()->getValueKind(); | |||
6621 | if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) { | |||
6622 | // DerivedToBase was already handled by the class-specific case above. | |||
6623 | // FIXME: Should we allow ObjC conversions here? | |||
6624 | const ReferenceConversions AllowedConversions = | |||
6625 | ReferenceConversions::Qualification | | |||
6626 | ReferenceConversions::NestedQualification | | |||
6627 | ReferenceConversions::Function; | |||
6628 | ||||
6629 | ReferenceConversions RefConv; | |||
6630 | if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) == | |||
6631 | Ref_Compatible && | |||
6632 | !(RefConv & ~AllowedConversions) && | |||
6633 | // [...] subject to the constraint that the reference must bind | |||
6634 | // directly [...] | |||
6635 | !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) { | |||
6636 | RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK); | |||
6637 | RTy = RHS.get()->getType(); | |||
6638 | } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) == | |||
6639 | Ref_Compatible && | |||
6640 | !(RefConv & ~AllowedConversions) && | |||
6641 | !LHS.get()->refersToBitField() && | |||
6642 | !LHS.get()->refersToVectorElement()) { | |||
6643 | LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK); | |||
6644 | LTy = LHS.get()->getType(); | |||
6645 | } | |||
6646 | } | |||
6647 | ||||
6648 | // C++11 [expr.cond]p4 | |||
6649 | // If the second and third operands are glvalues of the same value | |||
6650 | // category and have the same type, the result is of that type and | |||
6651 | // value category and it is a bit-field if the second or the third | |||
6652 | // operand is a bit-field, or if both are bit-fields. | |||
6653 | // We only extend this to bitfields, not to the crazy other kinds of | |||
6654 | // l-values. | |||
6655 | bool Same = Context.hasSameType(LTy, RTy); | |||
6656 | if (Same && LVK == RVK && LVK != VK_PRValue && | |||
6657 | LHS.get()->isOrdinaryOrBitFieldObject() && | |||
6658 | RHS.get()->isOrdinaryOrBitFieldObject()) { | |||
6659 | VK = LHS.get()->getValueKind(); | |||
6660 | if (LHS.get()->getObjectKind() == OK_BitField || | |||
6661 | RHS.get()->getObjectKind() == OK_BitField) | |||
6662 | OK = OK_BitField; | |||
6663 | return Context.getCommonSugaredType(LTy, RTy); | |||
6664 | } | |||
6665 | ||||
6666 | // C++11 [expr.cond]p5 | |||
6667 | // Otherwise, the result is a prvalue. If the second and third operands | |||
6668 | // do not have the same type, and either has (cv) class type, ... | |||
6669 | if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { | |||
6670 | // ... overload resolution is used to determine the conversions (if any) | |||
6671 | // to be applied to the operands. If the overload resolution fails, the | |||
6672 | // program is ill-formed. | |||
6673 | if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) | |||
6674 | return QualType(); | |||
6675 | } | |||
6676 | ||||
6677 | // C++11 [expr.cond]p6 | |||
6678 | // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard | |||
6679 | // conversions are performed on the second and third operands. | |||
6680 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
6681 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
6682 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
6683 | return QualType(); | |||
6684 | LTy = LHS.get()->getType(); | |||
6685 | RTy = RHS.get()->getType(); | |||
6686 | ||||
6687 | // After those conversions, one of the following shall hold: | |||
6688 | // -- The second and third operands have the same type; the result | |||
6689 | // is of that type. If the operands have class type, the result | |||
6690 | // is a prvalue temporary of the result type, which is | |||
6691 | // copy-initialized from either the second operand or the third | |||
6692 | // operand depending on the value of the first operand. | |||
6693 | if (Context.hasSameType(LTy, RTy)) { | |||
6694 | if (LTy->isRecordType()) { | |||
6695 | // The operands have class type. Make a temporary copy. | |||
6696 | ExprResult LHSCopy = PerformCopyInitialization( | |||
6697 | InitializedEntity::InitializeTemporary(LTy), SourceLocation(), LHS); | |||
6698 | if (LHSCopy.isInvalid()) | |||
6699 | return QualType(); | |||
6700 | ||||
6701 | ExprResult RHSCopy = PerformCopyInitialization( | |||
6702 | InitializedEntity::InitializeTemporary(RTy), SourceLocation(), RHS); | |||
6703 | if (RHSCopy.isInvalid()) | |||
6704 | return QualType(); | |||
6705 | ||||
6706 | LHS = LHSCopy; | |||
6707 | RHS = RHSCopy; | |||
6708 | } | |||
6709 | return Context.getCommonSugaredType(LTy, RTy); | |||
6710 | } | |||
6711 | ||||
6712 | // Extension: conditional operator involving vector types. | |||
6713 | if (LTy->isVectorType() || RTy->isVectorType()) | |||
6714 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, | |||
6715 | /*AllowBothBool*/ true, | |||
6716 | /*AllowBoolConversions*/ false, | |||
6717 | /*AllowBoolOperation*/ false, | |||
6718 | /*ReportInvalid*/ true); | |||
6719 | ||||
6720 | // -- The second and third operands have arithmetic or enumeration type; | |||
6721 | // the usual arithmetic conversions are performed to bring them to a | |||
6722 | // common type, and the result is of that type. | |||
6723 | if (LTy->isArithmeticType() && RTy->isArithmeticType()) { | |||
6724 | QualType ResTy = | |||
6725 | UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); | |||
6726 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
6727 | return QualType(); | |||
6728 | if (ResTy.isNull()) { | |||
6729 | Diag(QuestionLoc, | |||
6730 | diag::err_typecheck_cond_incompatible_operands) << LTy << RTy | |||
6731 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6732 | return QualType(); | |||
6733 | } | |||
6734 | ||||
6735 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); | |||
6736 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); | |||
6737 | ||||
6738 | return ResTy; | |||
6739 | } | |||
6740 | ||||
6741 | // -- The second and third operands have pointer type, or one has pointer | |||
6742 | // type and the other is a null pointer constant, or both are null | |||
6743 | // pointer constants, at least one of which is non-integral; pointer | |||
6744 | // conversions and qualification conversions are performed to bring them | |||
6745 | // to their composite pointer type. The result is of the composite | |||
6746 | // pointer type. | |||
6747 | // -- The second and third operands have pointer to member type, or one has | |||
6748 | // pointer to member type and the other is a null pointer constant; | |||
6749 | // pointer to member conversions and qualification conversions are | |||
6750 | // performed to bring them to a common type, whose cv-qualification | |||
6751 | // shall match the cv-qualification of either the second or the third | |||
6752 | // operand. The result is of the common type. | |||
6753 | QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS); | |||
6754 | if (!Composite.isNull()) | |||
6755 | return Composite; | |||
6756 | ||||
6757 | // Similarly, attempt to find composite type of two objective-c pointers. | |||
6758 | Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); | |||
6759 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
6760 | return QualType(); | |||
6761 | if (!Composite.isNull()) | |||
6762 | return Composite; | |||
6763 | ||||
6764 | // Check if we are using a null with a non-pointer type. | |||
6765 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | |||
6766 | return QualType(); | |||
6767 | ||||
6768 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | |||
6769 | << LHS.get()->getType() << RHS.get()->getType() | |||
6770 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6771 | return QualType(); | |||
6772 | } | |||
6773 | ||||
6774 | /// Find a merged pointer type and convert the two expressions to it. | |||
6775 | /// | |||
6776 | /// This finds the composite pointer type for \p E1 and \p E2 according to | |||
6777 | /// C++2a [expr.type]p3. It converts both expressions to this type and returns | |||
6778 | /// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs | |||
6779 | /// is \c true). | |||
6780 | /// | |||
6781 | /// \param Loc The location of the operator requiring these two expressions to | |||
6782 | /// be converted to the composite pointer type. | |||
6783 | /// | |||
6784 | /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type. | |||
6785 | QualType Sema::FindCompositePointerType(SourceLocation Loc, | |||
6786 | Expr *&E1, Expr *&E2, | |||
6787 | bool ConvertArgs) { | |||
6788 | assert(getLangOpts().CPlusPlus && "This function assumes C++")(static_cast <bool> (getLangOpts().CPlusPlus && "This function assumes C++") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"This function assumes C++\"" , "clang/lib/Sema/SemaExprCXX.cpp", 6788, __extension__ __PRETTY_FUNCTION__ )); | |||
6789 | ||||
6790 | // C++1z [expr]p14: | |||
6791 | // The composite pointer type of two operands p1 and p2 having types T1 | |||
6792 | // and T2 | |||
6793 | QualType T1 = E1->getType(), T2 = E2->getType(); | |||
6794 | ||||
6795 | // where at least one is a pointer or pointer to member type or | |||
6796 | // std::nullptr_t is: | |||
6797 | bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || | |||
6798 | T1->isNullPtrType(); | |||
6799 | bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || | |||
6800 | T2->isNullPtrType(); | |||
6801 | if (!T1IsPointerLike && !T2IsPointerLike) | |||
6802 | return QualType(); | |||
6803 | ||||
6804 | // - if both p1 and p2 are null pointer constants, std::nullptr_t; | |||
6805 | // This can't actually happen, following the standard, but we also use this | |||
6806 | // to implement the end of [expr.conv], which hits this case. | |||
6807 | // | |||
6808 | // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; | |||
6809 | if (T1IsPointerLike && | |||
6810 | E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { | |||
6811 | if (ConvertArgs) | |||
6812 | E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType() | |||
6813 | ? CK_NullToMemberPointer | |||
6814 | : CK_NullToPointer).get(); | |||
6815 | return T1; | |||
6816 | } | |||
6817 | if (T2IsPointerLike && | |||
6818 | E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { | |||
6819 | if (ConvertArgs) | |||
6820 | E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType() | |||
6821 | ? CK_NullToMemberPointer | |||
6822 | : CK_NullToPointer).get(); | |||
6823 | return T2; | |||
6824 | } | |||
6825 | ||||
6826 | // Now both have to be pointers or member pointers. | |||
6827 | if (!T1IsPointerLike || !T2IsPointerLike) | |||
6828 | return QualType(); | |||
6829 | assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&(static_cast <bool> (!T1->isNullPtrType() && !T2->isNullPtrType() && "nullptr_t should be a null pointer constant" ) ? void (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\"" , "clang/lib/Sema/SemaExprCXX.cpp", 6830, __extension__ __PRETTY_FUNCTION__ )) | |||
6830 | "nullptr_t should be a null pointer constant")(static_cast <bool> (!T1->isNullPtrType() && !T2->isNullPtrType() && "nullptr_t should be a null pointer constant" ) ? void (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\"" , "clang/lib/Sema/SemaExprCXX.cpp", 6830, __extension__ __PRETTY_FUNCTION__ )); | |||
6831 | ||||
6832 | struct Step { | |||
6833 | enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K; | |||
6834 | // Qualifiers to apply under the step kind. | |||
6835 | Qualifiers Quals; | |||
6836 | /// The class for a pointer-to-member; a constant array type with a bound | |||
6837 | /// (if any) for an array. | |||
6838 | const Type *ClassOrBound; | |||
6839 | ||||
6840 | Step(Kind K, const Type *ClassOrBound = nullptr) | |||
6841 | : K(K), ClassOrBound(ClassOrBound) {} | |||
6842 | QualType rebuild(ASTContext &Ctx, QualType T) const { | |||
6843 | T = Ctx.getQualifiedType(T, Quals); | |||
6844 | switch (K) { | |||
6845 | case Pointer: | |||
6846 | return Ctx.getPointerType(T); | |||
6847 | case MemberPointer: | |||
6848 | return Ctx.getMemberPointerType(T, ClassOrBound); | |||
6849 | case ObjCPointer: | |||
6850 | return Ctx.getObjCObjectPointerType(T); | |||
6851 | case Array: | |||
6852 | if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound)) | |||
6853 | return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr, | |||
6854 | ArrayType::Normal, 0); | |||
6855 | else | |||
6856 | return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0); | |||
6857 | } | |||
6858 | llvm_unreachable("unknown step kind")::llvm::llvm_unreachable_internal("unknown step kind", "clang/lib/Sema/SemaExprCXX.cpp" , 6858); | |||
6859 | } | |||
6860 | }; | |||
6861 | ||||
6862 | SmallVector<Step, 8> Steps; | |||
6863 | ||||
6864 | // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 | |||
6865 | // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), | |||
6866 | // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, | |||
6867 | // respectively; | |||
6868 | // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer | |||
6869 | // to member of C2 of type cv2 U2" for some non-function type U, where | |||
6870 | // C1 is reference-related to C2 or C2 is reference-related to C1, the | |||
6871 | // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2, | |||
6872 | // respectively; | |||
6873 | // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and | |||
6874 | // T2; | |||
6875 | // | |||
6876 | // Dismantle T1 and T2 to simultaneously determine whether they are similar | |||
6877 | // and to prepare to form the cv-combined type if so. | |||
6878 | QualType Composite1 = T1; | |||
6879 | QualType Composite2 = T2; | |||
6880 | unsigned NeedConstBefore = 0; | |||
6881 | while (true) { | |||
6882 | assert(!Composite1.isNull() && !Composite2.isNull())(static_cast <bool> (!Composite1.isNull() && !Composite2 .isNull()) ? void (0) : __assert_fail ("!Composite1.isNull() && !Composite2.isNull()" , "clang/lib/Sema/SemaExprCXX.cpp", 6882, __extension__ __PRETTY_FUNCTION__ )); | |||
6883 | ||||
6884 | Qualifiers Q1, Q2; | |||
6885 | Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1); | |||
6886 | Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2); | |||
6887 | ||||
6888 | // Top-level qualifiers are ignored. Merge at all lower levels. | |||
6889 | if (!Steps.empty()) { | |||
6890 | // Find the qualifier union: (approximately) the unique minimal set of | |||
6891 | // qualifiers that is compatible with both types. | |||
6892 | Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() | | |||
6893 | Q2.getCVRUQualifiers()); | |||
6894 | ||||
6895 | // Under one level of pointer or pointer-to-member, we can change to an | |||
6896 | // unambiguous compatible address space. | |||
6897 | if (Q1.getAddressSpace() == Q2.getAddressSpace()) { | |||
6898 | Quals.setAddressSpace(Q1.getAddressSpace()); | |||
6899 | } else if (Steps.size() == 1) { | |||
6900 | bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2); | |||
6901 | bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1); | |||
6902 | if (MaybeQ1 == MaybeQ2) { | |||
6903 | // Exception for ptr size address spaces. Should be able to choose | |||
6904 | // either address space during comparison. | |||
6905 | if (isPtrSizeAddressSpace(Q1.getAddressSpace()) || | |||
6906 | isPtrSizeAddressSpace(Q2.getAddressSpace())) | |||
6907 | MaybeQ1 = true; | |||
6908 | else | |||
6909 | return QualType(); // No unique best address space. | |||
6910 | } | |||
6911 | Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace() | |||
6912 | : Q2.getAddressSpace()); | |||
6913 | } else { | |||
6914 | return QualType(); | |||
6915 | } | |||
6916 | ||||
6917 | // FIXME: In C, we merge __strong and none to __strong at the top level. | |||
6918 | if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr()) | |||
6919 | Quals.setObjCGCAttr(Q1.getObjCGCAttr()); | |||
6920 | else if (T1->isVoidPointerType() || T2->isVoidPointerType()) | |||
6921 | assert(Steps.size() == 1)(static_cast <bool> (Steps.size() == 1) ? void (0) : __assert_fail ("Steps.size() == 1", "clang/lib/Sema/SemaExprCXX.cpp", 6921 , __extension__ __PRETTY_FUNCTION__)); | |||
6922 | else | |||
6923 | return QualType(); | |||
6924 | ||||
6925 | // Mismatched lifetime qualifiers never compatibly include each other. | |||
6926 | if (Q1.getObjCLifetime() == Q2.getObjCLifetime()) | |||
6927 | Quals.setObjCLifetime(Q1.getObjCLifetime()); | |||
6928 | else if (T1->isVoidPointerType() || T2->isVoidPointerType()) | |||
6929 | assert(Steps.size() == 1)(static_cast <bool> (Steps.size() == 1) ? void (0) : __assert_fail ("Steps.size() == 1", "clang/lib/Sema/SemaExprCXX.cpp", 6929 , __extension__ __PRETTY_FUNCTION__)); | |||
6930 | else | |||
6931 | return QualType(); | |||
6932 | ||||
6933 | Steps.back().Quals = Quals; | |||
6934 | if (Q1 != Quals || Q2 != Quals) | |||
6935 | NeedConstBefore = Steps.size() - 1; | |||
6936 | } | |||
6937 | ||||
6938 | // FIXME: Can we unify the following with UnwrapSimilarTypes? | |||
6939 | ||||
6940 | const ArrayType *Arr1, *Arr2; | |||
6941 | if ((Arr1 = Context.getAsArrayType(Composite1)) && | |||
6942 | (Arr2 = Context.getAsArrayType(Composite2))) { | |||
6943 | auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1); | |||
6944 | auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2); | |||
6945 | if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) { | |||
6946 | Composite1 = Arr1->getElementType(); | |||
6947 | Composite2 = Arr2->getElementType(); | |||
6948 | Steps.emplace_back(Step::Array, CAT1); | |||
6949 | continue; | |||
6950 | } | |||
6951 | bool IAT1 = isa<IncompleteArrayType>(Arr1); | |||
6952 | bool IAT2 = isa<IncompleteArrayType>(Arr2); | |||
6953 | if ((IAT1 && IAT2) || | |||
6954 | (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) && | |||
6955 | ((bool)CAT1 != (bool)CAT2) && | |||
6956 | (Steps.empty() || Steps.back().K != Step::Array))) { | |||
6957 | // In C++20 onwards, we can unify an array of N T with an array of | |||
6958 | // a different or unknown bound. But we can't form an array whose | |||
6959 | // element type is an array of unknown bound by doing so. | |||
6960 | Composite1 = Arr1->getElementType(); | |||
6961 | Composite2 = Arr2->getElementType(); | |||
6962 | Steps.emplace_back(Step::Array); | |||
6963 | if (CAT1 || CAT2) | |||
6964 | NeedConstBefore = Steps.size(); | |||
6965 | continue; | |||
6966 | } | |||
6967 | } | |||
6968 | ||||
6969 | const PointerType *Ptr1, *Ptr2; | |||
6970 | if ((Ptr1 = Composite1->getAs<PointerType>()) && | |||
6971 | (Ptr2 = Composite2->getAs<PointerType>())) { | |||
6972 | Composite1 = Ptr1->getPointeeType(); | |||
6973 | Composite2 = Ptr2->getPointeeType(); | |||
6974 | Steps.emplace_back(Step::Pointer); | |||
6975 | continue; | |||
6976 | } | |||
6977 | ||||
6978 | const ObjCObjectPointerType *ObjPtr1, *ObjPtr2; | |||
6979 | if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) && | |||
6980 | (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) { | |||
6981 | Composite1 = ObjPtr1->getPointeeType(); | |||
6982 | Composite2 = ObjPtr2->getPointeeType(); | |||
6983 | Steps.emplace_back(Step::ObjCPointer); | |||
6984 | continue; | |||
6985 | } | |||
6986 | ||||
6987 | const MemberPointerType *MemPtr1, *MemPtr2; | |||
6988 | if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && | |||
6989 | (MemPtr2 = Composite2->getAs<MemberPointerType>())) { | |||
6990 | Composite1 = MemPtr1->getPointeeType(); | |||
6991 | Composite2 = MemPtr2->getPointeeType(); | |||
6992 | ||||
6993 | // At the top level, we can perform a base-to-derived pointer-to-member | |||
6994 | // conversion: | |||
6995 | // | |||
6996 | // - [...] where C1 is reference-related to C2 or C2 is | |||
6997 | // reference-related to C1 | |||
6998 | // | |||
6999 | // (Note that the only kinds of reference-relatedness in scope here are | |||
7000 | // "same type or derived from".) At any other level, the class must | |||
7001 | // exactly match. | |||
7002 | const Type *Class = nullptr; | |||
7003 | QualType Cls1(MemPtr1->getClass(), 0); | |||
7004 | QualType Cls2(MemPtr2->getClass(), 0); | |||
7005 | if (Context.hasSameType(Cls1, Cls2)) | |||
7006 | Class = MemPtr1->getClass(); | |||
7007 | else if (Steps.empty()) | |||
7008 | Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() : | |||
7009 | IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr; | |||
7010 | if (!Class) | |||
7011 | return QualType(); | |||
7012 | ||||
7013 | Steps.emplace_back(Step::MemberPointer, Class); | |||
7014 | continue; | |||
7015 | } | |||
7016 | ||||
7017 | // Special case: at the top level, we can decompose an Objective-C pointer | |||
7018 | // and a 'cv void *'. Unify the qualifiers. | |||
7019 | if (Steps.empty() && ((Composite1->isVoidPointerType() && | |||
7020 | Composite2->isObjCObjectPointerType()) || | |||
7021 | (Composite1->isObjCObjectPointerType() && | |||
7022 | Composite2->isVoidPointerType()))) { | |||
7023 | Composite1 = Composite1->getPointeeType(); | |||
7024 | Composite2 = Composite2->getPointeeType(); | |||
7025 | Steps.emplace_back(Step::Pointer); | |||
7026 | continue; | |||
7027 | } | |||
7028 | ||||
7029 | // FIXME: block pointer types? | |||
7030 | ||||
7031 | // Cannot unwrap any more types. | |||
7032 | break; | |||
7033 | } | |||
7034 | ||||
7035 | // - if T1 or T2 is "pointer to noexcept function" and the other type is | |||
7036 | // "pointer to function", where the function types are otherwise the same, | |||
7037 | // "pointer to function"; | |||
7038 | // - if T1 or T2 is "pointer to member of C1 of type function", the other | |||
7039 | // type is "pointer to member of C2 of type noexcept function", and C1 | |||
7040 | // is reference-related to C2 or C2 is reference-related to C1, where | |||
7041 | // the function types are otherwise the same, "pointer to member of C2 of | |||
7042 | // type function" or "pointer to member of C1 of type function", | |||
7043 | // respectively; | |||
7044 | // | |||
7045 | // We also support 'noreturn' here, so as a Clang extension we generalize the | |||
7046 | // above to: | |||
7047 | // | |||
7048 | // - [Clang] If T1 and T2 are both of type "pointer to function" or | |||
7049 | // "pointer to member function" and the pointee types can be unified | |||
7050 | // by a function pointer conversion, that conversion is applied | |||
7051 | // before checking the following rules. | |||
7052 | // | |||
7053 | // We've already unwrapped down to the function types, and we want to merge | |||
7054 | // rather than just convert, so do this ourselves rather than calling | |||
7055 | // IsFunctionConversion. | |||
7056 | // | |||
7057 | // FIXME: In order to match the standard wording as closely as possible, we | |||
7058 | // currently only do this under a single level of pointers. Ideally, we would | |||
7059 | // allow this in general, and set NeedConstBefore to the relevant depth on | |||
7060 | // the side(s) where we changed anything. If we permit that, we should also | |||
7061 | // consider this conversion when determining type similarity and model it as | |||
7062 | // a qualification conversion. | |||
7063 | if (Steps.size() == 1) { | |||
7064 | if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { | |||
7065 | if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { | |||
7066 | FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); | |||
7067 | FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); | |||
7068 | ||||
7069 | // The result is noreturn if both operands are. | |||
7070 | bool Noreturn = | |||
7071 | EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); | |||
7072 | EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn); | |||
7073 | EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn); | |||
7074 | ||||
7075 | // The result is nothrow if both operands are. | |||
7076 | SmallVector<QualType, 8> ExceptionTypeStorage; | |||
7077 | EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs( | |||
7078 | EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage, | |||
7079 | getLangOpts().CPlusPlus17); | |||
7080 | ||||
7081 | Composite1 = Context.getFunctionType(FPT1->getReturnType(), | |||
7082 | FPT1->getParamTypes(), EPI1); | |||
7083 | Composite2 = Context.getFunctionType(FPT2->getReturnType(), | |||
7084 | FPT2->getParamTypes(), EPI2); | |||
7085 | } | |||
7086 | } | |||
7087 | } | |||
7088 | ||||
7089 | // There are some more conversions we can perform under exactly one pointer. | |||
7090 | if (Steps.size() == 1 && Steps.front().K == Step::Pointer && | |||
7091 | !Context.hasSameType(Composite1, Composite2)) { | |||
7092 | // - if T1 or T2 is "pointer to cv1 void" and the other type is | |||
7093 | // "pointer to cv2 T", where T is an object type or void, | |||
7094 | // "pointer to cv12 void", where cv12 is the union of cv1 and cv2; | |||
7095 | if (Composite1->isVoidType() && Composite2->isObjectType()) | |||
7096 | Composite2 = Composite1; | |||
7097 | else if (Composite2->isVoidType() && Composite1->isObjectType()) | |||
7098 | Composite1 = Composite2; | |||
7099 | // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 | |||
7100 | // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), | |||
7101 | // the cv-combined type of T1 and T2 or the cv-combined type of T2 and | |||
7102 | // T1, respectively; | |||
7103 | // | |||
7104 | // The "similar type" handling covers all of this except for the "T1 is a | |||
7105 | // base class of T2" case in the definition of reference-related. | |||
7106 | else if (IsDerivedFrom(Loc, Composite1, Composite2)) | |||
7107 | Composite1 = Composite2; | |||
7108 | else if (IsDerivedFrom(Loc, Composite2, Composite1)) | |||
7109 | Composite2 = Composite1; | |||
7110 | } | |||
7111 | ||||
7112 | // At this point, either the inner types are the same or we have failed to | |||
7113 | // find a composite pointer type. | |||
7114 | if (!Context.hasSameType(Composite1, Composite2)) | |||
7115 | return QualType(); | |||
7116 | ||||
7117 | // Per C++ [conv.qual]p3, add 'const' to every level before the last | |||
7118 | // differing qualifier. | |||
7119 | for (unsigned I = 0; I != NeedConstBefore; ++I) | |||
7120 | Steps[I].Quals.addConst(); | |||
7121 | ||||
7122 | // Rebuild the composite type. | |||
7123 | QualType Composite = Context.getCommonSugaredType(Composite1, Composite2); | |||
7124 | for (auto &S : llvm::reverse(Steps)) | |||
7125 | Composite = S.rebuild(Context, Composite); | |||
7126 | ||||
7127 | if (ConvertArgs) { | |||
7128 | // Convert the expressions to the composite pointer type. | |||
7129 | InitializedEntity Entity = | |||
7130 | InitializedEntity::InitializeTemporary(Composite); | |||
7131 | InitializationKind Kind = | |||
7132 | InitializationKind::CreateCopy(Loc, SourceLocation()); | |||
7133 | ||||
7134 | InitializationSequence E1ToC(*this, Entity, Kind, E1); | |||
7135 | if (!E1ToC) | |||
7136 | return QualType(); | |||
7137 | ||||
7138 | InitializationSequence E2ToC(*this, Entity, Kind, E2); | |||
7139 | if (!E2ToC) | |||
7140 | return QualType(); | |||
7141 | ||||
7142 | // FIXME: Let the caller know if these fail to avoid duplicate diagnostics. | |||
7143 | ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1); | |||
7144 | if (E1Result.isInvalid()) | |||
7145 | return QualType(); | |||
7146 | E1 = E1Result.get(); | |||
7147 | ||||
7148 | ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2); | |||
7149 | if (E2Result.isInvalid()) | |||
7150 | return QualType(); | |||
7151 | E2 = E2Result.get(); | |||
7152 | } | |||
7153 | ||||
7154 | return Composite; | |||
7155 | } | |||
7156 | ||||
7157 | ExprResult Sema::MaybeBindToTemporary(Expr *E) { | |||
7158 | if (!E) | |||
7159 | return ExprError(); | |||
7160 | ||||
7161 | assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?")(static_cast <bool> (!isa<CXXBindTemporaryExpr>(E ) && "Double-bound temporary?") ? void (0) : __assert_fail ("!isa<CXXBindTemporaryExpr>(E) && \"Double-bound temporary?\"" , "clang/lib/Sema/SemaExprCXX.cpp", 7161, __extension__ __PRETTY_FUNCTION__ )); | |||
7162 | ||||
7163 | // If the result is a glvalue, we shouldn't bind it. | |||
7164 | if (E->isGLValue()) | |||
7165 | return E; | |||
7166 | ||||
7167 | // In ARC, calls that return a retainable type can return retained, | |||
7168 | // in which case we have to insert a consuming cast. | |||
7169 | if (getLangOpts().ObjCAutoRefCount && | |||
7170 | E->getType()->isObjCRetainableType()) { | |||
7171 | ||||
7172 | bool ReturnsRetained; | |||
7173 | ||||
7174 | // For actual calls, we compute this by examining the type of the | |||
7175 | // called value. | |||
7176 | if (CallExpr *Call = dyn_cast<CallExpr>(E)) { | |||
7177 | Expr *Callee = Call->getCallee()->IgnoreParens(); | |||
7178 | QualType T = Callee->getType(); | |||
7179 | ||||
7180 | if (T == Context.BoundMemberTy) { | |||
7181 | // Handle pointer-to-members. | |||
7182 | if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) | |||
7183 | T = BinOp->getRHS()->getType(); | |||
7184 | else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) | |||
7185 | T = Mem->getMemberDecl()->getType(); | |||
7186 | } | |||
7187 | ||||
7188 | if (const PointerType *Ptr = T->getAs<PointerType>()) | |||
7189 | T = Ptr->getPointeeType(); | |||
7190 | else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) | |||
7191 | T = Ptr->getPointeeType(); | |||
7192 | else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) | |||
7193 | T = MemPtr->getPointeeType(); | |||
7194 | ||||
7195 | auto *FTy = T->castAs<FunctionType>(); | |||
7196 | ReturnsRetained = FTy->getExtInfo().getProducesResult(); | |||
7197 | ||||
7198 | // ActOnStmtExpr arranges things so that StmtExprs of retainable | |||
7199 | // type always produce a +1 object. | |||
7200 | } else if (isa<StmtExpr>(E)) { | |||
7201 | ReturnsRetained = true; | |||
7202 | ||||
7203 | // We hit this case with the lambda conversion-to-block optimization; | |||
7204 | // we don't want any extra casts here. | |||
7205 | } else if (isa<CastExpr>(E) && | |||
7206 | isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { | |||
7207 | return E; | |||
7208 | ||||
7209 | // For message sends and property references, we try to find an | |||
7210 | // actual method. FIXME: we should infer retention by selector in | |||
7211 | // cases where we don't have an actual method. | |||
7212 | } else { | |||
7213 | ObjCMethodDecl *D = nullptr; | |||
7214 | if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { | |||
7215 | D = Send->getMethodDecl(); | |||
7216 | } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { | |||
7217 | D = BoxedExpr->getBoxingMethod(); | |||
7218 | } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { | |||
7219 | // Don't do reclaims if we're using the zero-element array | |||
7220 | // constant. | |||
7221 | if (ArrayLit->getNumElements() == 0 && | |||
7222 | Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) | |||
7223 | return E; | |||
7224 | ||||
7225 | D = ArrayLit->getArrayWithObjectsMethod(); | |||
7226 | } else if (ObjCDictionaryLiteral *DictLit | |||
7227 | = dyn_cast<ObjCDictionaryLiteral>(E)) { | |||
7228 | // Don't do reclaims if we're using the zero-element dictionary | |||
7229 | // constant. | |||
7230 | if (DictLit->getNumElements() == 0 && | |||
7231 | Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) | |||
7232 | return E; | |||
7233 | ||||
7234 | D = DictLit->getDictWithObjectsMethod(); | |||
7235 | } | |||
7236 | ||||
7237 | ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); | |||
7238 | ||||
7239 | // Don't do reclaims on performSelector calls; despite their | |||
7240 | // return type, the invoked method doesn't necessarily actually | |||
7241 | // return an object. | |||
7242 | if (!ReturnsRetained && | |||
7243 | D && D->getMethodFamily() == OMF_performSelector) | |||
7244 | return E; | |||
7245 | } | |||
7246 | ||||
7247 | // Don't reclaim an object of Class type. | |||
7248 | if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) | |||
7249 | return E; | |||
7250 | ||||
7251 | Cleanup.setExprNeedsCleanups(true); | |||
7252 | ||||
7253 | CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject | |||
7254 | : CK_ARCReclaimReturnedObject); | |||
7255 | return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr, | |||
7256 | VK_PRValue, FPOptionsOverride()); | |||
7257 | } | |||
7258 | ||||
7259 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
7260 | Cleanup.setExprNeedsCleanups(true); | |||
7261 | ||||
7262 | if (!getLangOpts().CPlusPlus) | |||
7263 | return E; | |||
7264 | ||||
7265 | // Search for the base element type (cf. ASTContext::getBaseElementType) with | |||
7266 | // a fast path for the common case that the type is directly a RecordType. | |||
7267 | const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); | |||
7268 | const RecordType *RT = nullptr; | |||
7269 | while (!RT) { | |||
7270 | switch (T->getTypeClass()) { | |||
7271 | case Type::Record: | |||
7272 | RT = cast<RecordType>(T); | |||
7273 | break; | |||
7274 | case Type::ConstantArray: | |||
7275 | case Type::IncompleteArray: | |||
7276 | case Type::VariableArray: | |||
7277 | case Type::DependentSizedArray: | |||
7278 | T = cast<ArrayType>(T)->getElementType().getTypePtr(); | |||
7279 | break; | |||
7280 | default: | |||
7281 | return E; | |||
7282 | } | |||
7283 | } | |||
7284 | ||||
7285 | // That should be enough to guarantee that this type is complete, if we're | |||
7286 | // not processing a decltype expression. | |||
7287 | CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | |||
7288 | if (RD->isInvalidDecl() || RD->isDependentContext()) | |||
7289 | return E; | |||
7290 | ||||
7291 | bool IsDecltype = ExprEvalContexts.back().ExprContext == | |||
7292 | ExpressionEvaluationContextRecord::EK_Decltype; | |||
7293 | CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD); | |||
7294 | ||||
7295 | if (Destructor) { | |||
7296 | MarkFunctionReferenced(E->getExprLoc(), Destructor); | |||
7297 | CheckDestructorAccess(E->getExprLoc(), Destructor, | |||
7298 | PDiag(diag::err_access_dtor_temp) | |||
7299 | << E->getType()); | |||
7300 | if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) | |||
7301 | return ExprError(); | |||
7302 | ||||
7303 | // If destructor is trivial, we can avoid the extra copy. | |||
7304 | if (Destructor->isTrivial()) | |||
7305 | return E; | |||
7306 | ||||
7307 | // We need a cleanup, but we don't need to remember the temporary. | |||
7308 | Cleanup.setExprNeedsCleanups(true); | |||
7309 | } | |||
7310 | ||||
7311 | CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); | |||
7312 | CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); | |||
7313 | ||||
7314 | if (IsDecltype) | |||
7315 | ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); | |||
7316 | ||||
7317 | return Bind; | |||
7318 | } | |||
7319 | ||||
7320 | ExprResult | |||
7321 | Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { | |||
7322 | if (SubExpr.isInvalid()) | |||
7323 | return ExprError(); | |||
7324 | ||||
7325 | return MaybeCreateExprWithCleanups(SubExpr.get()); | |||
7326 | } | |||
7327 | ||||
7328 | Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { | |||
7329 | assert(SubExpr && "subexpression can't be null!")(static_cast <bool> (SubExpr && "subexpression can't be null!" ) ? void (0) : __assert_fail ("SubExpr && \"subexpression can't be null!\"" , "clang/lib/Sema/SemaExprCXX.cpp", 7329, __extension__ __PRETTY_FUNCTION__ )); | |||
7330 | ||||
7331 | CleanupVarDeclMarking(); | |||
7332 | ||||
7333 | unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; | |||
7334 | assert(ExprCleanupObjects.size() >= FirstCleanup)(static_cast <bool> (ExprCleanupObjects.size() >= FirstCleanup ) ? void (0) : __assert_fail ("ExprCleanupObjects.size() >= FirstCleanup" , "clang/lib/Sema/SemaExprCXX.cpp", 7334, __extension__ __PRETTY_FUNCTION__ )); | |||
7335 | assert(Cleanup.exprNeedsCleanups() ||(static_cast <bool> (Cleanup.exprNeedsCleanups() || ExprCleanupObjects .size() == FirstCleanup) ? void (0) : __assert_fail ("Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup" , "clang/lib/Sema/SemaExprCXX.cpp", 7336, __extension__ __PRETTY_FUNCTION__ )) | |||
7336 | ExprCleanupObjects.size() == FirstCleanup)(static_cast <bool> (Cleanup.exprNeedsCleanups() || ExprCleanupObjects .size() == FirstCleanup) ? void (0) : __assert_fail ("Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup" , "clang/lib/Sema/SemaExprCXX.cpp", 7336, __extension__ __PRETTY_FUNCTION__ )); | |||
7337 | if (!Cleanup.exprNeedsCleanups()) | |||
7338 | return SubExpr; | |||
7339 | ||||
7340 | auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup, | |||
7341 | ExprCleanupObjects.size() - FirstCleanup); | |||
7342 | ||||
7343 | auto *E = ExprWithCleanups::Create( | |||
7344 | Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups); | |||
7345 | DiscardCleanupsInEvaluationContext(); | |||
7346 | ||||
7347 | return E; | |||
7348 | } | |||
7349 | ||||
7350 | Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { | |||
7351 | assert(SubStmt && "sub-statement can't be null!")(static_cast <bool> (SubStmt && "sub-statement can't be null!" ) ? void (0) : __assert_fail ("SubStmt && \"sub-statement can't be null!\"" , "clang/lib/Sema/SemaExprCXX.cpp", 7351, __extension__ __PRETTY_FUNCTION__ )); | |||
7352 | ||||
7353 | CleanupVarDeclMarking(); | |||
7354 | ||||
7355 | if (!Cleanup.exprNeedsCleanups()) | |||
7356 | return SubStmt; | |||
7357 | ||||
7358 | // FIXME: In order to attach the temporaries, wrap the statement into | |||
7359 | // a StmtExpr; currently this is only used for asm statements. | |||
7360 | // This is hacky, either create a new CXXStmtWithTemporaries statement or | |||
7361 | // a new AsmStmtWithTemporaries. | |||
7362 | CompoundStmt *CompStmt = | |||
7363 | CompoundStmt::Create(Context, SubStmt, FPOptionsOverride(), | |||
7364 | SourceLocation(), SourceLocation()); | |||
7365 | Expr *E = new (Context) | |||
7366 | StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(), | |||
7367 | /*FIXME TemplateDepth=*/0); | |||
7368 | return MaybeCreateExprWithCleanups(E); | |||
7369 | } | |||
7370 | ||||
7371 | /// Process the expression contained within a decltype. For such expressions, | |||
7372 | /// certain semantic checks on temporaries are delayed until this point, and | |||
7373 | /// are omitted for the 'topmost' call in the decltype expression. If the | |||
7374 | /// topmost call bound a temporary, strip that temporary off the expression. | |||
7375 | ExprResult Sema::ActOnDecltypeExpression(Expr *E) { | |||
7376 | assert(ExprEvalContexts.back().ExprContext ==(static_cast <bool> (ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && "not in a decltype expression") ? void (0) : __assert_fail ( "ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\"" , "clang/lib/Sema/SemaExprCXX.cpp", 7378, __extension__ __PRETTY_FUNCTION__ )) | |||
7377 | ExpressionEvaluationContextRecord::EK_Decltype &&(static_cast <bool> (ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && "not in a decltype expression") ? void (0) : __assert_fail ( "ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\"" , "clang/lib/Sema/SemaExprCXX.cpp", 7378, __extension__ __PRETTY_FUNCTION__ )) | |||
7378 | "not in a decltype expression")(static_cast <bool> (ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && "not in a decltype expression") ? void (0) : __assert_fail ( "ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\"" , "clang/lib/Sema/SemaExprCXX.cpp", 7378, __extension__ __PRETTY_FUNCTION__ )); | |||
7379 | ||||
7380 | ExprResult Result = CheckPlaceholderExpr(E); | |||
7381 | if (Result.isInvalid()) | |||
7382 | return ExprError(); | |||
7383 | E = Result.get(); | |||
7384 | ||||
7385 | // C++11 [expr.call]p11: | |||
7386 | // If a function call is a prvalue of object type, | |||
7387 | // -- if the function call is either | |||
7388 | // -- the operand of a decltype-specifier, or | |||
7389 | // -- the right operand of a comma operator that is the operand of a | |||
7390 | // decltype-specifier, | |||
7391 | // a temporary object is not introduced for the prvalue. | |||
7392 | ||||
7393 | // Recursively rebuild ParenExprs and comma expressions to strip out the | |||
7394 | // outermost CXXBindTemporaryExpr, if any. | |||
7395 | if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | |||
7396 | ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); | |||
7397 | if (SubExpr.isInvalid()) | |||
7398 | return ExprError(); | |||
7399 | if (SubExpr.get() == PE->getSubExpr()) | |||
7400 | return E; | |||
7401 | return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); | |||
7402 | } | |||
7403 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
7404 | if (BO->getOpcode() == BO_Comma) { | |||
7405 | ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); | |||
7406 | if (RHS.isInvalid()) | |||
7407 | return ExprError(); | |||
7408 | if (RHS.get() == BO->getRHS()) | |||
7409 | return E; | |||
7410 | return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma, | |||
7411 | BO->getType(), BO->getValueKind(), | |||
7412 | BO->getObjectKind(), BO->getOperatorLoc(), | |||
7413 | BO->getFPFeatures()); | |||
7414 | } | |||
7415 | } | |||
7416 | ||||
7417 | CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); | |||
7418 | CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr()) | |||
7419 | : nullptr; | |||
7420 | if (TopCall) | |||
7421 | E = TopCall; | |||
7422 | else | |||
7423 | TopBind = nullptr; | |||
7424 | ||||
7425 | // Disable the special decltype handling now. | |||
7426 | ExprEvalContexts.back().ExprContext = | |||
7427 | ExpressionEvaluationContextRecord::EK_Other; | |||
7428 | ||||
7429 | Result = CheckUnevaluatedOperand(E); | |||
7430 | if (Result.isInvalid()) | |||
7431 | return ExprError(); | |||
7432 | E = Result.get(); | |||
7433 | ||||
7434 | // In MS mode, don't perform any extra checking of call return types within a | |||
7435 | // decltype expression. | |||
7436 | if (getLangOpts().MSVCCompat) | |||
7437 | return E; | |||
7438 | ||||
7439 | // Perform the semantic checks we delayed until this point. | |||
7440 | for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); | |||
7441 | I != N; ++I) { | |||
7442 | CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; | |||
7443 | if (Call == TopCall) | |||
7444 | continue; | |||
7445 | ||||
7446 | if (CheckCallReturnType(Call->getCallReturnType(Context), | |||
7447 | Call->getBeginLoc(), Call, Call->getDirectCallee())) | |||
7448 | return ExprError(); | |||
7449 | } | |||
7450 | ||||
7451 | // Now all relevant types are complete, check the destructors are accessible | |||
7452 | // and non-deleted, and annotate them on the temporaries. | |||
7453 | for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); | |||
7454 | I != N; ++I) { | |||
7455 | CXXBindTemporaryExpr *Bind = | |||
7456 | ExprEvalContexts.back().DelayedDecltypeBinds[I]; | |||
7457 | if (Bind == TopBind) | |||
7458 | continue; | |||
7459 | ||||
7460 | CXXTemporary *Temp = Bind->getTemporary(); | |||
7461 | ||||
7462 | CXXRecordDecl *RD = | |||
7463 | Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | |||
7464 | CXXDestructorDecl *Destructor = LookupDestructor(RD); | |||
7465 | Temp->setDestructor(Destructor); | |||
7466 | ||||
7467 | MarkFunctionReferenced(Bind->getExprLoc(), Destructor); | |||
7468 | CheckDestructorAccess(Bind->getExprLoc(), Destructor, | |||
7469 | PDiag(diag::err_access_dtor_temp) | |||
7470 | << Bind->getType()); | |||
7471 | if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc())) | |||
7472 | return ExprError(); | |||
7473 | ||||
7474 | // We need a cleanup, but we don't need to remember the temporary. | |||
7475 | Cleanup.setExprNeedsCleanups(true); | |||
7476 | } | |||
7477 | ||||
7478 | // Possibly strip off the top CXXBindTemporaryExpr. | |||
7479 | return E; | |||
7480 | } | |||
7481 | ||||
7482 | /// Note a set of 'operator->' functions that were used for a member access. | |||
7483 | static void noteOperatorArrows(Sema &S, | |||
7484 | ArrayRef<FunctionDecl *> OperatorArrows) { | |||
7485 | unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; | |||
7486 | // FIXME: Make this configurable? | |||
7487 | unsigned Limit = 9; | |||
7488 | if (OperatorArrows.size() > Limit) { | |||
7489 | // Produce Limit-1 normal notes and one 'skipping' note. | |||
7490 | SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; | |||
7491 | SkipCount = OperatorArrows.size() - (Limit - 1); | |||
7492 | } | |||
7493 | ||||
7494 | for (unsigned I = 0; I < OperatorArrows.size(); /**/) { | |||
7495 | if (I == SkipStart) { | |||
7496 | S.Diag(OperatorArrows[I]->getLocation(), | |||
7497 | diag::note_operator_arrows_suppressed) | |||
7498 | << SkipCount; | |||
7499 | I += SkipCount; | |||
7500 | } else { | |||
7501 | S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) | |||
7502 | << OperatorArrows[I]->getCallResultType(); | |||
7503 | ++I; | |||
7504 | } | |||
7505 | } | |||
7506 | } | |||
7507 | ||||
7508 | ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, | |||
7509 | SourceLocation OpLoc, | |||
7510 | tok::TokenKind OpKind, | |||
7511 | ParsedType &ObjectType, | |||
7512 | bool &MayBePseudoDestructor) { | |||
7513 | // Since this might be a postfix expression, get rid of ParenListExprs. | |||
7514 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); | |||
7515 | if (Result.isInvalid()) return ExprError(); | |||
7516 | Base = Result.get(); | |||
7517 | ||||
7518 | Result = CheckPlaceholderExpr(Base); | |||
7519 | if (Result.isInvalid()) return ExprError(); | |||
7520 | Base = Result.get(); | |||
7521 | ||||
7522 | QualType BaseType = Base->getType(); | |||
7523 | MayBePseudoDestructor = false; | |||
7524 | if (BaseType->isDependentType()) { | |||
7525 | // If we have a pointer to a dependent type and are using the -> operator, | |||
7526 | // the object type is the type that the pointer points to. We might still | |||
7527 | // have enough information about that type to do something useful. | |||
7528 | if (OpKind == tok::arrow) | |||
7529 | if (const PointerType *Ptr = BaseType->getAs<PointerType>()) | |||
7530 | BaseType = Ptr->getPointeeType(); | |||
7531 | ||||
7532 | ObjectType = ParsedType::make(BaseType); | |||
7533 | MayBePseudoDestructor = true; | |||
7534 | return Base; | |||
7535 | } | |||
7536 | ||||
7537 | // C++ [over.match.oper]p8: | |||
7538 | // [...] When operator->returns, the operator-> is applied to the value | |||
7539 | // returned, with the original second operand. | |||
7540 | if (OpKind == tok::arrow) { | |||
7541 | QualType StartingType = BaseType; | |||
7542 | bool NoArrowOperatorFound = false; | |||
7543 | bool FirstIteration = true; | |||
7544 | FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext); | |||
7545 | // The set of types we've considered so far. | |||
7546 | llvm::SmallPtrSet<CanQualType,8> CTypes; | |||
7547 | SmallVector<FunctionDecl*, 8> OperatorArrows; | |||
7548 | CTypes.insert(Context.getCanonicalType(BaseType)); | |||
7549 | ||||
7550 | while (BaseType->isRecordType()) { | |||
7551 | if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { | |||
7552 | Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) | |||
7553 | << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); | |||
7554 | noteOperatorArrows(*this, OperatorArrows); | |||
7555 | Diag(OpLoc, diag::note_operator_arrow_depth) | |||
7556 | << getLangOpts().ArrowDepth; | |||
7557 | return ExprError(); | |||
7558 | } | |||
7559 | ||||
7560 | Result = BuildOverloadedArrowExpr( | |||
7561 | S, Base, OpLoc, | |||
7562 | // When in a template specialization and on the first loop iteration, | |||
7563 | // potentially give the default diagnostic (with the fixit in a | |||
7564 | // separate note) instead of having the error reported back to here | |||
7565 | // and giving a diagnostic with a fixit attached to the error itself. | |||
7566 | (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) | |||
7567 | ? nullptr | |||
7568 | : &NoArrowOperatorFound); | |||
7569 | if (Result.isInvalid()) { | |||
7570 | if (NoArrowOperatorFound) { | |||
7571 | if (FirstIteration) { | |||
7572 | Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) | |||
7573 | << BaseType << 1 << Base->getSourceRange() | |||
7574 | << FixItHint::CreateReplacement(OpLoc, "."); | |||
7575 | OpKind = tok::period; | |||
7576 | break; | |||
7577 | } | |||
7578 | Diag(OpLoc, diag::err_typecheck_member_reference_arrow) | |||
7579 | << BaseType << Base->getSourceRange(); | |||
7580 | CallExpr *CE = dyn_cast<CallExpr>(Base); | |||
7581 | if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { | |||
7582 | Diag(CD->getBeginLoc(), | |||
7583 | diag::note_member_reference_arrow_from_operator_arrow); | |||
7584 | } | |||
7585 | } | |||
7586 | return ExprError(); | |||
7587 | } | |||
7588 | Base = Result.get(); | |||
7589 | if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) | |||
7590 | OperatorArrows.push_back(OpCall->getDirectCallee()); | |||
7591 | BaseType = Base->getType(); | |||
7592 | CanQualType CBaseType = Context.getCanonicalType(BaseType); | |||
7593 | if (!CTypes.insert(CBaseType).second) { | |||
7594 | Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; | |||
7595 | noteOperatorArrows(*this, OperatorArrows); | |||
7596 | return ExprError(); | |||
7597 | } | |||
7598 | FirstIteration = false; | |||
7599 | } | |||
7600 | ||||
7601 | if (OpKind == tok::arrow) { | |||
7602 | if (BaseType->isPointerType()) | |||
7603 | BaseType = BaseType->getPointeeType(); | |||
7604 | else if (auto *AT = Context.getAsArrayType(BaseType)) | |||
7605 | BaseType = AT->getElementType(); | |||
7606 | } | |||
7607 | } | |||
7608 | ||||
7609 | // Objective-C properties allow "." access on Objective-C pointer types, | |||
7610 | // so adjust the base type to the object type itself. | |||
7611 | if (BaseType->isObjCObjectPointerType()) | |||
7612 | BaseType = BaseType->getPointeeType(); | |||
7613 | ||||
7614 | // C++ [basic.lookup.classref]p2: | |||
7615 | // [...] If the type of the object expression is of pointer to scalar | |||
7616 | // type, the unqualified-id is looked up in the context of the complete | |||
7617 | // postfix-expression. | |||
7618 | // | |||
7619 | // This also indicates that we could be parsing a pseudo-destructor-name. | |||
7620 | // Note that Objective-C class and object types can be pseudo-destructor | |||
7621 | // expressions or normal member (ivar or property) access expressions, and | |||
7622 | // it's legal for the type to be incomplete if this is a pseudo-destructor | |||
7623 | // call. We'll do more incomplete-type checks later in the lookup process, | |||
7624 | // so just skip this check for ObjC types. | |||
7625 | if (!BaseType->isRecordType()) { | |||
7626 | ObjectType = ParsedType::make(BaseType); | |||
7627 | MayBePseudoDestructor = true; | |||
7628 | return Base; | |||
7629 | } | |||
7630 | ||||
7631 | // The object type must be complete (or dependent), or | |||
7632 | // C++11 [expr.prim.general]p3: | |||
7633 | // Unlike the object expression in other contexts, *this is not required to | |||
7634 | // be of complete type for purposes of class member access (5.2.5) outside | |||
7635 | // the member function body. | |||
7636 | if (!BaseType->isDependentType() && | |||
7637 | !isThisOutsideMemberFunctionBody(BaseType) && | |||
7638 | RequireCompleteType(OpLoc, BaseType, | |||
7639 | diag::err_incomplete_member_access)) { | |||
7640 | return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base}); | |||
7641 | } | |||
7642 | ||||
7643 | // C++ [basic.lookup.classref]p2: | |||
7644 | // If the id-expression in a class member access (5.2.5) is an | |||
7645 | // unqualified-id, and the type of the object expression is of a class | |||
7646 | // type C (or of pointer to a class type C), the unqualified-id is looked | |||
7647 | // up in the scope of class C. [...] | |||
7648 | ObjectType = ParsedType::make(BaseType); | |||
7649 | return Base; | |||
7650 | } | |||
7651 | ||||
7652 | static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, | |||
7653 | tok::TokenKind &OpKind, SourceLocation OpLoc) { | |||
7654 | if (Base->hasPlaceholderType()) { | |||
7655 | ExprResult result = S.CheckPlaceholderExpr(Base); | |||
7656 | if (result.isInvalid()) return true; | |||
7657 | Base = result.get(); | |||
7658 | } | |||
7659 | ObjectType = Base->getType(); | |||
7660 | ||||
7661 | // C++ [expr.pseudo]p2: | |||
7662 | // The left-hand side of the dot operator shall be of scalar type. The | |||
7663 | // left-hand side of the arrow operator shall be of pointer to scalar type. | |||
7664 | // This scalar type is the object type. | |||
7665 | // Note that this is rather different from the normal handling for the | |||
7666 | // arrow operator. | |||
7667 | if (OpKind == tok::arrow) { | |||
7668 | // The operator requires a prvalue, so perform lvalue conversions. | |||
7669 | // Only do this if we might plausibly end with a pointer, as otherwise | |||
7670 | // this was likely to be intended to be a '.'. | |||
7671 | if (ObjectType->isPointerType() || ObjectType->isArrayType() || | |||
7672 | ObjectType->isFunctionType()) { | |||
7673 | ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base); | |||
7674 | if (BaseResult.isInvalid()) | |||
7675 | return true; | |||
7676 | Base = BaseResult.get(); | |||
7677 | ObjectType = Base->getType(); | |||
7678 | } | |||
7679 | ||||
7680 | if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { | |||
7681 | ObjectType = Ptr->getPointeeType(); | |||
7682 | } else if (!Base->isTypeDependent()) { | |||
7683 | // The user wrote "p->" when they probably meant "p."; fix it. | |||
7684 | S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) | |||
7685 | << ObjectType << true | |||
7686 | << FixItHint::CreateReplacement(OpLoc, "."); | |||
7687 | if (S.isSFINAEContext()) | |||
7688 | return true; | |||
7689 | ||||
7690 | OpKind = tok::period; | |||
7691 | } | |||
7692 | } | |||
7693 | ||||
7694 | return false; | |||
7695 | } | |||
7696 | ||||
7697 | /// Check if it's ok to try and recover dot pseudo destructor calls on | |||
7698 | /// pointer objects. | |||
7699 | static bool | |||
7700 | canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, | |||
7701 | QualType DestructedType) { | |||
7702 | // If this is a record type, check if its destructor is callable. | |||
7703 | if (auto *RD = DestructedType->getAsCXXRecordDecl()) { | |||
7704 | if (RD->hasDefinition()) | |||
7705 | if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD)) | |||
7706 | return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false); | |||
7707 | return false; | |||
7708 | } | |||
7709 | ||||
7710 | // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor. | |||
7711 | return DestructedType->isDependentType() || DestructedType->isScalarType() || | |||
7712 | DestructedType->isVectorType(); | |||
7713 | } | |||
7714 | ||||
7715 | ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, | |||
7716 | SourceLocation OpLoc, | |||
7717 | tok::TokenKind OpKind, | |||
7718 | const CXXScopeSpec &SS, | |||
7719 | TypeSourceInfo *ScopeTypeInfo, | |||
7720 | SourceLocation CCLoc, | |||
7721 | SourceLocation TildeLoc, | |||
7722 | PseudoDestructorTypeStorage Destructed) { | |||
7723 | TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); | |||
7724 | ||||
7725 | QualType ObjectType; | |||
7726 | if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) | |||
7727 | return ExprError(); | |||
7728 | ||||
7729 | if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && | |||
7730 | !ObjectType->isVectorType()) { | |||
7731 | if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) | |||
7732 | Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); | |||
7733 | else { | |||
7734 | Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) | |||
7735 | << ObjectType << Base->getSourceRange(); | |||
7736 | return ExprError(); | |||
7737 | } | |||
7738 | } | |||
7739 | ||||
7740 | // C++ [expr.pseudo]p2: | |||
7741 | // [...] The cv-unqualified versions of the object type and of the type | |||
7742 | // designated by the pseudo-destructor-name shall be the same type. | |||
7743 | if (DestructedTypeInfo) { | |||
7744 | QualType DestructedType = DestructedTypeInfo->getType(); | |||
7745 | SourceLocation DestructedTypeStart = | |||
7746 | DestructedTypeInfo->getTypeLoc().getBeginLoc(); | |||
7747 | if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { | |||
7748 | if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { | |||
7749 | // Detect dot pseudo destructor calls on pointer objects, e.g.: | |||
7750 | // Foo *foo; | |||
7751 | // foo.~Foo(); | |||
7752 | if (OpKind == tok::period && ObjectType->isPointerType() && | |||
7753 | Context.hasSameUnqualifiedType(DestructedType, | |||
7754 | ObjectType->getPointeeType())) { | |||
7755 | auto Diagnostic = | |||
7756 | Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) | |||
7757 | << ObjectType << /*IsArrow=*/0 << Base->getSourceRange(); | |||
7758 | ||||
7759 | // Issue a fixit only when the destructor is valid. | |||
7760 | if (canRecoverDotPseudoDestructorCallsOnPointerObjects( | |||
7761 | *this, DestructedType)) | |||
7762 | Diagnostic << FixItHint::CreateReplacement(OpLoc, "->"); | |||
7763 | ||||
7764 | // Recover by setting the object type to the destructed type and the | |||
7765 | // operator to '->'. | |||
7766 | ObjectType = DestructedType; | |||
7767 | OpKind = tok::arrow; | |||
7768 | } else { | |||
7769 | Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) | |||
7770 | << ObjectType << DestructedType << Base->getSourceRange() | |||
7771 | << DestructedTypeInfo->getTypeLoc().getSourceRange(); | |||
7772 | ||||
7773 | // Recover by setting the destructed type to the object type. | |||
7774 | DestructedType = ObjectType; | |||
7775 | DestructedTypeInfo = | |||
7776 | Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); | |||
7777 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); | |||
7778 | } | |||
7779 | } else if (DestructedType.getObjCLifetime() != | |||
7780 | ObjectType.getObjCLifetime()) { | |||
7781 | ||||
7782 | if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { | |||
7783 | // Okay: just pretend that the user provided the correctly-qualified | |||
7784 | // type. | |||
7785 | } else { | |||
7786 | Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) | |||
7787 | << ObjectType << DestructedType << Base->getSourceRange() | |||
7788 | << DestructedTypeInfo->getTypeLoc().getSourceRange(); | |||
7789 | } | |||
7790 | ||||
7791 | // Recover by setting the destructed type to the object type. | |||
7792 | DestructedType = ObjectType; | |||
7793 | DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, | |||
7794 | DestructedTypeStart); | |||
7795 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); | |||
7796 | } | |||
7797 | } | |||
7798 | } | |||
7799 | ||||
7800 | // C++ [expr.pseudo]p2: | |||
7801 | // [...] Furthermore, the two type-names in a pseudo-destructor-name of the | |||
7802 | // form | |||
7803 | // | |||
7804 | // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name | |||
7805 | // | |||
7806 | // shall designate the same scalar type. | |||
7807 | if (ScopeTypeInfo) { | |||
7808 | QualType ScopeType = ScopeTypeInfo->getType(); | |||
7809 | if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && | |||
7810 | !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { | |||
7811 | ||||
7812 | Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(), | |||
7813 | diag::err_pseudo_dtor_type_mismatch) | |||
7814 | << ObjectType << ScopeType << Base->getSourceRange() | |||
7815 | << ScopeTypeInfo->getTypeLoc().getSourceRange(); | |||
7816 | ||||
7817 | ScopeType = QualType(); | |||
7818 | ScopeTypeInfo = nullptr; | |||
7819 | } | |||
7820 | } | |||
7821 | ||||
7822 | Expr *Result | |||
7823 | = new (Context) CXXPseudoDestructorExpr(Context, Base, | |||
7824 | OpKind == tok::arrow, OpLoc, | |||
7825 | SS.getWithLocInContext(Context), | |||
7826 | ScopeTypeInfo, | |||
7827 | CCLoc, | |||
7828 | TildeLoc, | |||
7829 | Destructed); | |||
7830 | ||||
7831 | return Result; | |||
7832 | } | |||
7833 | ||||
7834 | ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, | |||
7835 | SourceLocation OpLoc, | |||
7836 | tok::TokenKind OpKind, | |||
7837 | CXXScopeSpec &SS, | |||
7838 | UnqualifiedId &FirstTypeName, | |||
7839 | SourceLocation CCLoc, | |||
7840 | SourceLocation TildeLoc, | |||
7841 | UnqualifiedId &SecondTypeName) { | |||
7842 | assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||(static_cast <bool> ((FirstTypeName.getKind() == UnqualifiedIdKind ::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind ::IK_Identifier) && "Invalid first type name in pseudo-destructor" ) ? void (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\"" , "clang/lib/Sema/SemaExprCXX.cpp", 7844, __extension__ __PRETTY_FUNCTION__ )) | |||
7843 | FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&(static_cast <bool> ((FirstTypeName.getKind() == UnqualifiedIdKind ::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind ::IK_Identifier) && "Invalid first type name in pseudo-destructor" ) ? void (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\"" , "clang/lib/Sema/SemaExprCXX.cpp", 7844, __extension__ __PRETTY_FUNCTION__ )) | |||
7844 | "Invalid first type name in pseudo-destructor")(static_cast <bool> ((FirstTypeName.getKind() == UnqualifiedIdKind ::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind ::IK_Identifier) && "Invalid first type name in pseudo-destructor" ) ? void (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\"" , "clang/lib/Sema/SemaExprCXX.cpp", 7844, __extension__ __PRETTY_FUNCTION__ )); | |||
7845 | assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||(static_cast <bool> ((SecondTypeName.getKind() == UnqualifiedIdKind ::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind ::IK_Identifier) && "Invalid second type name in pseudo-destructor" ) ? void (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\"" , "clang/lib/Sema/SemaExprCXX.cpp", 7847, __extension__ __PRETTY_FUNCTION__ )) | |||
7846 | SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&(static_cast <bool> ((SecondTypeName.getKind() == UnqualifiedIdKind ::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind ::IK_Identifier) && "Invalid second type name in pseudo-destructor" ) ? void (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\"" , "clang/lib/Sema/SemaExprCXX.cpp", 7847, __extension__ __PRETTY_FUNCTION__ )) | |||
7847 | "Invalid second type name in pseudo-destructor")(static_cast <bool> ((SecondTypeName.getKind() == UnqualifiedIdKind ::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind ::IK_Identifier) && "Invalid second type name in pseudo-destructor" ) ? void (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\"" , "clang/lib/Sema/SemaExprCXX.cpp", 7847, __extension__ __PRETTY_FUNCTION__ )); | |||
7848 | ||||
7849 | QualType ObjectType; | |||
7850 | if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) | |||
7851 | return ExprError(); | |||
7852 | ||||
7853 | // Compute the object type that we should use for name lookup purposes. Only | |||
7854 | // record types and dependent types matter. | |||
7855 | ParsedType ObjectTypePtrForLookup; | |||
7856 | if (!SS.isSet()) { | |||
7857 | if (ObjectType->isRecordType()) | |||
7858 | ObjectTypePtrForLookup = ParsedType::make(ObjectType); | |||
7859 | else if (ObjectType->isDependentType()) | |||
7860 | ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); | |||
7861 | } | |||
7862 | ||||
7863 | // Convert the name of the type being destructed (following the ~) into a | |||
7864 | // type (with source-location information). | |||
7865 | QualType DestructedType; | |||
7866 | TypeSourceInfo *DestructedTypeInfo = nullptr; | |||
7867 | PseudoDestructorTypeStorage Destructed; | |||
7868 | if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { | |||
7869 | ParsedType T = getTypeName(*SecondTypeName.Identifier, | |||
7870 | SecondTypeName.StartLocation, | |||
7871 | S, &SS, true, false, ObjectTypePtrForLookup, | |||
7872 | /*IsCtorOrDtorName*/true); | |||
7873 | if (!T && | |||
7874 | ((SS.isSet() && !computeDeclContext(SS, false)) || | |||
7875 | (!SS.isSet() && ObjectType->isDependentType()))) { | |||
7876 | // The name of the type being destroyed is a dependent name, and we | |||
7877 | // couldn't find anything useful in scope. Just store the identifier and | |||
7878 | // it's location, and we'll perform (qualified) name lookup again at | |||
7879 | // template instantiation time. | |||
7880 | Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, | |||
7881 | SecondTypeName.StartLocation); | |||
7882 | } else if (!T) { | |||
7883 | Diag(SecondTypeName.StartLocation, | |||
7884 | diag::err_pseudo_dtor_destructor_non_type) | |||
7885 | << SecondTypeName.Identifier << ObjectType; | |||
7886 | if (isSFINAEContext()) | |||
7887 | return ExprError(); | |||
7888 | ||||
7889 | // Recover by assuming we had the right type all along. | |||
7890 | DestructedType = ObjectType; | |||
7891 | } else | |||
7892 | DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); | |||
7893 | } else { | |||
7894 | // Resolve the template-id to a type. | |||
7895 | TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; | |||
7896 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
7897 | TemplateId->NumArgs); | |||
7898 | TypeResult T = ActOnTemplateIdType(S, | |||
7899 | SS, | |||
7900 | TemplateId->TemplateKWLoc, | |||
7901 | TemplateId->Template, | |||
7902 | TemplateId->Name, | |||
7903 | TemplateId->TemplateNameLoc, | |||
7904 | TemplateId->LAngleLoc, | |||
7905 | TemplateArgsPtr, | |||
7906 | TemplateId->RAngleLoc, | |||
7907 | /*IsCtorOrDtorName*/true); | |||
7908 | if (T.isInvalid() || !T.get()) { | |||
7909 | // Recover by assuming we had the right type all along. | |||
7910 | DestructedType = ObjectType; | |||
7911 | } else | |||
7912 | DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); | |||
7913 | } | |||
7914 | ||||
7915 | // If we've performed some kind of recovery, (re-)build the type source | |||
7916 | // information. | |||
7917 | if (!DestructedType.isNull()) { | |||
7918 | if (!DestructedTypeInfo) | |||
7919 | DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, | |||
7920 | SecondTypeName.StartLocation); | |||
7921 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); | |||
7922 | } | |||
7923 | ||||
7924 | // Convert the name of the scope type (the type prior to '::') into a type. | |||
7925 | TypeSourceInfo *ScopeTypeInfo = nullptr; | |||
7926 | QualType ScopeType; | |||
7927 | if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || | |||
7928 | FirstTypeName.Identifier) { | |||
7929 | if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { | |||
7930 | ParsedType T = getTypeName(*FirstTypeName.Identifier, | |||
7931 | FirstTypeName.StartLocation, | |||
7932 | S, &SS, true, false, ObjectTypePtrForLookup, | |||
7933 | /*IsCtorOrDtorName*/true); | |||
7934 | if (!T) { | |||
7935 | Diag(FirstTypeName.StartLocation, | |||
7936 | diag::err_pseudo_dtor_destructor_non_type) | |||
7937 | << FirstTypeName.Identifier << ObjectType; | |||
7938 | ||||
7939 | if (isSFINAEContext()) | |||
7940 | return ExprError(); | |||
7941 | ||||
7942 | // Just drop this type. It's unnecessary anyway. | |||
7943 | ScopeType = QualType(); | |||
7944 | } else | |||
7945 | ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); | |||
7946 | } else { | |||
7947 | // Resolve the template-id to a type. | |||
7948 | TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; | |||
7949 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
7950 | TemplateId->NumArgs); | |||
7951 | TypeResult T = ActOnTemplateIdType(S, | |||
7952 | SS, | |||
7953 | TemplateId->TemplateKWLoc, | |||
7954 | TemplateId->Template, | |||
7955 | TemplateId->Name, | |||
7956 | TemplateId->TemplateNameLoc, | |||
7957 | TemplateId->LAngleLoc, | |||
7958 | TemplateArgsPtr, | |||
7959 | TemplateId->RAngleLoc, | |||
7960 | /*IsCtorOrDtorName*/true); | |||
7961 | if (T.isInvalid() || !T.get()) { | |||
7962 | // Recover by dropping this type. | |||
7963 | ScopeType = QualType(); | |||
7964 | } else | |||
7965 | ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); | |||
7966 | } | |||
7967 | } | |||
7968 | ||||
7969 | if (!ScopeType.isNull() && !ScopeTypeInfo) | |||
7970 | ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, | |||
7971 | FirstTypeName.StartLocation); | |||
7972 | ||||
7973 | ||||
7974 | return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, | |||
7975 | ScopeTypeInfo, CCLoc, TildeLoc, | |||
7976 | Destructed); | |||
7977 | } | |||
7978 | ||||
7979 | ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, | |||
7980 | SourceLocation OpLoc, | |||
7981 | tok::TokenKind OpKind, | |||
7982 | SourceLocation TildeLoc, | |||
7983 | const DeclSpec& DS) { | |||
7984 | QualType ObjectType; | |||
7985 | if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) | |||
7986 | return ExprError(); | |||
7987 | ||||
7988 | if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { | |||
7989 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); | |||
7990 | return true; | |||
7991 | } | |||
7992 | ||||
7993 | QualType T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false); | |||
7994 | ||||
7995 | TypeLocBuilder TLB; | |||
7996 | DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); | |||
7997 | DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); | |||
7998 | DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); | |||
7999 | TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); | |||
8000 | PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); | |||
8001 | ||||
8002 | return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), | |||
8003 | nullptr, SourceLocation(), TildeLoc, | |||
8004 | Destructed); | |||
8005 | } | |||
8006 | ||||
8007 | ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, | |||
8008 | CXXConversionDecl *Method, | |||
8009 | bool HadMultipleCandidates) { | |||
8010 | // Convert the expression to match the conversion function's implicit object | |||
8011 | // parameter. | |||
8012 | ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr, | |||
8013 | FoundDecl, Method); | |||
8014 | if (Exp.isInvalid()) | |||
8015 | return true; | |||
8016 | ||||
8017 | if (Method->getParent()->isLambda() && | |||
8018 | Method->getConversionType()->isBlockPointerType()) { | |||
8019 | // This is a lambda conversion to block pointer; check if the argument | |||
8020 | // was a LambdaExpr. | |||
8021 | Expr *SubE = E; | |||
8022 | CastExpr *CE = dyn_cast<CastExpr>(SubE); | |||
8023 | if (CE && CE->getCastKind() == CK_NoOp) | |||
8024 | SubE = CE->getSubExpr(); | |||
8025 | SubE = SubE->IgnoreParens(); | |||
8026 | if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) | |||
8027 | SubE = BE->getSubExpr(); | |||
8028 | if (isa<LambdaExpr>(SubE)) { | |||
8029 | // For the conversion to block pointer on a lambda expression, we | |||
8030 | // construct a special BlockLiteral instead; this doesn't really make | |||
8031 | // a difference in ARC, but outside of ARC the resulting block literal | |||
8032 | // follows the normal lifetime rules for block literals instead of being | |||
8033 | // autoreleased. | |||
8034 | PushExpressionEvaluationContext( | |||
8035 | ExpressionEvaluationContext::PotentiallyEvaluated); | |||
8036 | ExprResult BlockExp = BuildBlockForLambdaConversion( | |||
8037 | Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); | |||
8038 | PopExpressionEvaluationContext(); | |||
8039 | ||||
8040 | // FIXME: This note should be produced by a CodeSynthesisContext. | |||
8041 | if (BlockExp.isInvalid()) | |||
8042 | Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); | |||
8043 | return BlockExp; | |||
8044 | } | |||
8045 | } | |||
8046 | ||||
8047 | MemberExpr *ME = | |||
8048 | BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(), | |||
8049 | NestedNameSpecifierLoc(), SourceLocation(), Method, | |||
8050 | DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), | |||
8051 | HadMultipleCandidates, DeclarationNameInfo(), | |||
8052 | Context.BoundMemberTy, VK_PRValue, OK_Ordinary); | |||
8053 | ||||
8054 | QualType ResultType = Method->getReturnType(); | |||
8055 | ExprValueKind VK = Expr::getValueKindForType(ResultType); | |||
8056 | ResultType = ResultType.getNonLValueExprType(Context); | |||
8057 | ||||
8058 | CXXMemberCallExpr *CE = CXXMemberCallExpr::Create( | |||
8059 | Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc(), | |||
8060 | CurFPFeatureOverrides()); | |||
8061 | ||||
8062 | if (CheckFunctionCall(Method, CE, | |||
8063 | Method->getType()->castAs<FunctionProtoType>())) | |||
8064 | return ExprError(); | |||
8065 | ||||
8066 | return CheckForImmediateInvocation(CE, CE->getMethodDecl()); | |||
8067 | } | |||
8068 | ||||
8069 | ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, | |||
8070 | SourceLocation RParen) { | |||
8071 | // If the operand is an unresolved lookup expression, the expression is ill- | |||
8072 | // formed per [over.over]p1, because overloaded function names cannot be used | |||
8073 | // without arguments except in explicit contexts. | |||
8074 | ExprResult R = CheckPlaceholderExpr(Operand); | |||
8075 | if (R.isInvalid()) | |||
8076 | return R; | |||
8077 | ||||
8078 | R = CheckUnevaluatedOperand(R.get()); | |||
8079 | if (R.isInvalid()) | |||
8080 | return ExprError(); | |||
8081 | ||||
8082 | Operand = R.get(); | |||
8083 | ||||
8084 | if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() && | |||
8085 | Operand->HasSideEffects(Context, false)) { | |||
8086 | // The expression operand for noexcept is in an unevaluated expression | |||
8087 | // context, so side effects could result in unintended consequences. | |||
8088 | Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); | |||
8089 | } | |||
8090 | ||||
8091 | CanThrowResult CanThrow = canThrow(Operand); | |||
8092 | return new (Context) | |||
8093 | CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); | |||
8094 | } | |||
8095 | ||||
8096 | ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, | |||
8097 | Expr *Operand, SourceLocation RParen) { | |||
8098 | return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); | |||
8099 | } | |||
8100 | ||||
8101 | static void MaybeDecrementCount( | |||
8102 | Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { | |||
8103 | DeclRefExpr *LHS = nullptr; | |||
8104 | bool IsCompoundAssign = false; | |||
8105 | bool isIncrementDecrementUnaryOp = false; | |||
8106 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
8107 | if (BO->getLHS()->getType()->isDependentType() || | |||
8108 | BO->getRHS()->getType()->isDependentType()) { | |||
8109 | if (BO->getOpcode() != BO_Assign) | |||
8110 | return; | |||
8111 | } else if (!BO->isAssignmentOp()) | |||
8112 | return; | |||
8113 | else | |||
8114 | IsCompoundAssign = BO->isCompoundAssignmentOp(); | |||
8115 | LHS = dyn_cast<DeclRefExpr>(BO->getLHS()); | |||
8116 | } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) { | |||
8117 | if (COCE->getOperator() != OO_Equal) | |||
8118 | return; | |||
8119 | LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0)); | |||
8120 | } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | |||
8121 | if (!UO->isIncrementDecrementOp()) | |||
8122 | return; | |||
8123 | isIncrementDecrementUnaryOp = true; | |||
8124 | LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr()); | |||
8125 | } | |||
8126 | if (!LHS) | |||
8127 | return; | |||
8128 | VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl()); | |||
8129 | if (!VD) | |||
8130 | return; | |||
8131 | // Don't decrement RefsMinusAssignments if volatile variable with compound | |||
8132 | // assignment (+=, ...) or increment/decrement unary operator to avoid | |||
8133 | // potential unused-but-set-variable warning. | |||
8134 | if ((IsCompoundAssign || isIncrementDecrementUnaryOp) && | |||
8135 | VD->getType().isVolatileQualified()) | |||
8136 | return; | |||
8137 | auto iter = RefsMinusAssignments.find(VD); | |||
8138 | if (iter == RefsMinusAssignments.end()) | |||
8139 | return; | |||
8140 | iter->getSecond()--; | |||
8141 | } | |||
8142 | ||||
8143 | /// Perform the conversions required for an expression used in a | |||
8144 | /// context that ignores the result. | |||
8145 | ExprResult Sema::IgnoredValueConversions(Expr *E) { | |||
8146 | MaybeDecrementCount(E, RefsMinusAssignments); | |||
8147 | ||||
8148 | if (E->hasPlaceholderType()) { | |||
8149 | ExprResult result = CheckPlaceholderExpr(E); | |||
8150 | if (result.isInvalid()) return E; | |||
8151 | E = result.get(); | |||
8152 | } | |||
8153 | ||||
8154 | // C99 6.3.2.1: | |||
8155 | // [Except in specific positions,] an lvalue that does not have | |||
8156 | // array type is converted to the value stored in the | |||
8157 | // designated object (and is no longer an lvalue). | |||
8158 | if (E->isPRValue()) { | |||
8159 | // In C, function designators (i.e. expressions of function type) | |||
8160 | // are r-values, but we still want to do function-to-pointer decay | |||
8161 | // on them. This is both technically correct and convenient for | |||
8162 | // some clients. | |||
8163 | if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) | |||
8164 | return DefaultFunctionArrayConversion(E); | |||
8165 | ||||
8166 | return E; | |||
8167 | } | |||
8168 | ||||
8169 | if (getLangOpts().CPlusPlus) { | |||
8170 | // The C++11 standard defines the notion of a discarded-value expression; | |||
8171 | // normally, we don't need to do anything to handle it, but if it is a | |||
8172 | // volatile lvalue with a special form, we perform an lvalue-to-rvalue | |||
8173 | // conversion. | |||
8174 | if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) { | |||
8175 | ExprResult Res = DefaultLvalueConversion(E); | |||
8176 | if (Res.isInvalid()) | |||
8177 | return E; | |||
8178 | E = Res.get(); | |||
8179 | } else { | |||
8180 | // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if | |||
8181 | // it occurs as a discarded-value expression. | |||
8182 | CheckUnusedVolatileAssignment(E); | |||
8183 | } | |||
8184 | ||||
8185 | // C++1z: | |||
8186 | // If the expression is a prvalue after this optional conversion, the | |||
8187 | // temporary materialization conversion is applied. | |||
8188 | // | |||
8189 | // We skip this step: IR generation is able to synthesize the storage for | |||
8190 | // itself in the aggregate case, and adding the extra node to the AST is | |||
8191 | // just clutter. | |||
8192 | // FIXME: We don't emit lifetime markers for the temporaries due to this. | |||
8193 | // FIXME: Do any other AST consumers care about this? | |||
8194 | return E; | |||
8195 | } | |||
8196 | ||||
8197 | // GCC seems to also exclude expressions of incomplete enum type. | |||
8198 | if (const EnumType *T = E->getType()->getAs<EnumType>()) { | |||
8199 | if (!T->getDecl()->isComplete()) { | |||
8200 | // FIXME: stupid workaround for a codegen bug! | |||
8201 | E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get(); | |||
8202 | return E; | |||
8203 | } | |||
8204 | } | |||
8205 | ||||
8206 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | |||
8207 | if (Res.isInvalid()) | |||
8208 | return E; | |||
8209 | E = Res.get(); | |||
8210 | ||||
8211 | if (!E->getType()->isVoidType()) | |||
8212 | RequireCompleteType(E->getExprLoc(), E->getType(), | |||
8213 | diag::err_incomplete_type); | |||
8214 | return E; | |||
8215 | } | |||
8216 | ||||
8217 | ExprResult Sema::CheckUnevaluatedOperand(Expr *E) { | |||
8218 | // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if | |||
8219 | // it occurs as an unevaluated operand. | |||
8220 | CheckUnusedVolatileAssignment(E); | |||
8221 | ||||
8222 | return E; | |||
8223 | } | |||
8224 | ||||
8225 | // If we can unambiguously determine whether Var can never be used | |||
8226 | // in a constant expression, return true. | |||
8227 | // - if the variable and its initializer are non-dependent, then | |||
8228 | // we can unambiguously check if the variable is a constant expression. | |||
8229 | // - if the initializer is not value dependent - we can determine whether | |||
8230 | // it can be used to initialize a constant expression. If Init can not | |||
8231 | // be used to initialize a constant expression we conclude that Var can | |||
8232 | // never be a constant expression. | |||
8233 | // - FXIME: if the initializer is dependent, we can still do some analysis and | |||
8234 | // identify certain cases unambiguously as non-const by using a Visitor: | |||
8235 | // - such as those that involve odr-use of a ParmVarDecl, involve a new | |||
8236 | // delete, lambda-expr, dynamic-cast, reinterpret-cast etc... | |||
8237 | static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, | |||
8238 | ASTContext &Context) { | |||
8239 | if (isa<ParmVarDecl>(Var)) return true; | |||
8240 | const VarDecl *DefVD = nullptr; | |||
8241 | ||||
8242 | // If there is no initializer - this can not be a constant expression. | |||
8243 | if (!Var->getAnyInitializer(DefVD)) return true; | |||
8244 | assert(DefVD)(static_cast <bool> (DefVD) ? void (0) : __assert_fail ( "DefVD", "clang/lib/Sema/SemaExprCXX.cpp", 8244, __extension__ __PRETTY_FUNCTION__)); | |||
8245 | if (DefVD->isWeak()) return false; | |||
8246 | EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); | |||
8247 | ||||
8248 | Expr *Init = cast<Expr>(Eval->Value); | |||
8249 | ||||
8250 | if (Var->getType()->isDependentType() || Init->isValueDependent()) { | |||
8251 | // FIXME: Teach the constant evaluator to deal with the non-dependent parts | |||
8252 | // of value-dependent expressions, and use it here to determine whether the | |||
8253 | // initializer is a potential constant expression. | |||
8254 | return false; | |||
8255 | } | |||
8256 | ||||
8257 | return !Var->isUsableInConstantExpressions(Context); | |||
8258 | } | |||
8259 | ||||
8260 | /// Check if the current lambda has any potential captures | |||
8261 | /// that must be captured by any of its enclosing lambdas that are ready to | |||
8262 | /// capture. If there is a lambda that can capture a nested | |||
8263 | /// potential-capture, go ahead and do so. Also, check to see if any | |||
8264 | /// variables are uncaptureable or do not involve an odr-use so do not | |||
8265 | /// need to be captured. | |||
8266 | ||||
8267 | static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( | |||
8268 | Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { | |||
8269 | ||||
8270 | assert(!S.isUnevaluatedContext())(static_cast <bool> (!S.isUnevaluatedContext()) ? void ( 0) : __assert_fail ("!S.isUnevaluatedContext()", "clang/lib/Sema/SemaExprCXX.cpp" , 8270, __extension__ __PRETTY_FUNCTION__)); | |||
8271 | assert(S.CurContext->isDependentContext())(static_cast <bool> (S.CurContext->isDependentContext ()) ? void (0) : __assert_fail ("S.CurContext->isDependentContext()" , "clang/lib/Sema/SemaExprCXX.cpp", 8271, __extension__ __PRETTY_FUNCTION__ )); | |||
8272 | #ifndef NDEBUG | |||
8273 | DeclContext *DC = S.CurContext; | |||
8274 | while (DC && isa<CapturedDecl>(DC)) | |||
8275 | DC = DC->getParent(); | |||
8276 | assert((static_cast <bool> (CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext" ) ? void (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\"" , "clang/lib/Sema/SemaExprCXX.cpp", 8278, __extension__ __PRETTY_FUNCTION__ )) | |||
8277 | CurrentLSI->CallOperator == DC &&(static_cast <bool> (CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext" ) ? void (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\"" , "clang/lib/Sema/SemaExprCXX.cpp", 8278, __extension__ __PRETTY_FUNCTION__ )) | |||
8278 | "The current call operator must be synchronized with Sema's CurContext")(static_cast <bool> (CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext" ) ? void (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\"" , "clang/lib/Sema/SemaExprCXX.cpp", 8278, __extension__ __PRETTY_FUNCTION__ )); | |||
8279 | #endif // NDEBUG | |||
8280 | ||||
8281 | const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); | |||
8282 | ||||
8283 | // All the potentially captureable variables in the current nested | |||
8284 | // lambda (within a generic outer lambda), must be captured by an | |||
8285 | // outer lambda that is enclosed within a non-dependent context. | |||
8286 | CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) { | |||
8287 | // If the variable is clearly identified as non-odr-used and the full | |||
8288 | // expression is not instantiation dependent, only then do we not | |||
8289 | // need to check enclosing lambda's for speculative captures. | |||
8290 | // For e.g.: | |||
8291 | // Even though 'x' is not odr-used, it should be captured. | |||
8292 | // int test() { | |||
8293 | // const int x = 10; | |||
8294 | // auto L = [=](auto a) { | |||
8295 | // (void) +x + a; | |||
8296 | // }; | |||
8297 | // } | |||
8298 | if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && | |||
8299 | !IsFullExprInstantiationDependent) | |||
8300 | return; | |||
8301 | ||||
8302 | VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl(); | |||
8303 | if (!UnderlyingVar) | |||
8304 | return; | |||
8305 | ||||
8306 | // If we have a capture-capable lambda for the variable, go ahead and | |||
8307 | // capture the variable in that lambda (and all its enclosing lambdas). | |||
8308 | if (const Optional<unsigned> Index = | |||
8309 | getStackIndexOfNearestEnclosingCaptureCapableLambda( | |||
8310 | S.FunctionScopes, Var, S)) | |||
8311 | S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index); | |||
8312 | const bool IsVarNeverAConstantExpression = | |||
8313 | VariableCanNeverBeAConstantExpression(UnderlyingVar, S.Context); | |||
8314 | if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { | |||
8315 | // This full expression is not instantiation dependent or the variable | |||
8316 | // can not be used in a constant expression - which means | |||
8317 | // this variable must be odr-used here, so diagnose a | |||
8318 | // capture violation early, if the variable is un-captureable. | |||
8319 | // This is purely for diagnosing errors early. Otherwise, this | |||
8320 | // error would get diagnosed when the lambda becomes capture ready. | |||
8321 | QualType CaptureType, DeclRefType; | |||
8322 | SourceLocation ExprLoc = VarExpr->getExprLoc(); | |||
8323 | if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, | |||
8324 | /*EllipsisLoc*/ SourceLocation(), | |||
8325 | /*BuildAndDiagnose*/false, CaptureType, | |||
8326 | DeclRefType, nullptr)) { | |||
8327 | // We will never be able to capture this variable, and we need | |||
8328 | // to be able to in any and all instantiations, so diagnose it. | |||
8329 | S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, | |||
8330 | /*EllipsisLoc*/ SourceLocation(), | |||
8331 | /*BuildAndDiagnose*/true, CaptureType, | |||
8332 | DeclRefType, nullptr); | |||
8333 | } | |||
8334 | } | |||
8335 | }); | |||
8336 | ||||
8337 | // Check if 'this' needs to be captured. | |||
8338 | if (CurrentLSI->hasPotentialThisCapture()) { | |||
8339 | // If we have a capture-capable lambda for 'this', go ahead and capture | |||
8340 | // 'this' in that lambda (and all its enclosing lambdas). | |||
8341 | if (const Optional<unsigned> Index = | |||
8342 | getStackIndexOfNearestEnclosingCaptureCapableLambda( | |||
8343 | S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) { | |||
8344 | const unsigned FunctionScopeIndexOfCapturableLambda = *Index; | |||
8345 | S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, | |||
8346 | /*Explicit*/ false, /*BuildAndDiagnose*/ true, | |||
8347 | &FunctionScopeIndexOfCapturableLambda); | |||
8348 | } | |||
8349 | } | |||
8350 | ||||
8351 | // Reset all the potential captures at the end of each full-expression. | |||
8352 | CurrentLSI->clearPotentialCaptures(); | |||
8353 | } | |||
8354 | ||||
8355 | static ExprResult attemptRecovery(Sema &SemaRef, | |||
8356 | const TypoCorrectionConsumer &Consumer, | |||
8357 | const TypoCorrection &TC) { | |||
8358 | LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(), | |||
8359 | Consumer.getLookupResult().getLookupKind()); | |||
8360 | const CXXScopeSpec *SS = Consumer.getSS(); | |||
8361 | CXXScopeSpec NewSS; | |||
8362 | ||||
8363 | // Use an approprate CXXScopeSpec for building the expr. | |||
8364 | if (auto *NNS = TC.getCorrectionSpecifier()) | |||
8365 | NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange()); | |||
8366 | else if (SS && !TC.WillReplaceSpecifier()) | |||
8367 | NewSS = *SS; | |||
8368 | ||||
8369 | if (auto *ND = TC.getFoundDecl()) { | |||
8370 | R.setLookupName(ND->getDeclName()); | |||
8371 | R.addDecl(ND); | |||
8372 | if (ND->isCXXClassMember()) { | |||
8373 | // Figure out the correct naming class to add to the LookupResult. | |||
8374 | CXXRecordDecl *Record = nullptr; | |||
8375 | if (auto *NNS = TC.getCorrectionSpecifier()) | |||
8376 | Record = NNS->getAsType()->getAsCXXRecordDecl(); | |||
8377 | if (!Record) | |||
8378 | Record = | |||
8379 | dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext()); | |||
8380 | if (Record) | |||
8381 | R.setNamingClass(Record); | |||
8382 | ||||
8383 | // Detect and handle the case where the decl might be an implicit | |||
8384 | // member. | |||
8385 | bool MightBeImplicitMember; | |||
8386 | if (!Consumer.isAddressOfOperand()) | |||
8387 | MightBeImplicitMember = true; | |||
8388 | else if (!NewSS.isEmpty()) | |||
8389 | MightBeImplicitMember = false; | |||
8390 | else if (R.isOverloadedResult()) | |||
8391 | MightBeImplicitMember = false; | |||
8392 | else if (R.isUnresolvableResult()) | |||
8393 | MightBeImplicitMember = true; | |||
8394 | else | |||
8395 | MightBeImplicitMember = isa<FieldDecl>(ND) || | |||
8396 | isa<IndirectFieldDecl>(ND) || | |||
8397 | isa<MSPropertyDecl>(ND); | |||
8398 | ||||
8399 | if (MightBeImplicitMember) | |||
8400 | return SemaRef.BuildPossibleImplicitMemberExpr( | |||
8401 | NewSS, /*TemplateKWLoc*/ SourceLocation(), R, | |||
8402 | /*TemplateArgs*/ nullptr, /*S*/ nullptr); | |||
8403 | } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { | |||
8404 | return SemaRef.LookupInObjCMethod(R, Consumer.getScope(), | |||
8405 | Ivar->getIdentifier()); | |||
8406 | } | |||
8407 | } | |||
8408 | ||||
8409 | return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false, | |||
8410 | /*AcceptInvalidDecl*/ true); | |||
8411 | } | |||
8412 | ||||
8413 | namespace { | |||
8414 | class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> { | |||
8415 | llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; | |||
8416 | ||||
8417 | public: | |||
8418 | explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs) | |||
8419 | : TypoExprs(TypoExprs) {} | |||
8420 | bool VisitTypoExpr(TypoExpr *TE) { | |||
8421 | TypoExprs.insert(TE); | |||
8422 | return true; | |||
8423 | } | |||
8424 | }; | |||
8425 | ||||
8426 | class TransformTypos : public TreeTransform<TransformTypos> { | |||
8427 | typedef TreeTransform<TransformTypos> BaseTransform; | |||
8428 | ||||
8429 | VarDecl *InitDecl; // A decl to avoid as a correction because it is in the | |||
8430 | // process of being initialized. | |||
8431 | llvm::function_ref<ExprResult(Expr *)> ExprFilter; | |||
8432 | llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs; | |||
8433 | llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache; | |||
8434 | llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution; | |||
8435 | ||||
8436 | /// Emit diagnostics for all of the TypoExprs encountered. | |||
8437 | /// | |||
8438 | /// If the TypoExprs were successfully corrected, then the diagnostics should | |||
8439 | /// suggest the corrections. Otherwise the diagnostics will not suggest | |||
8440 | /// anything (having been passed an empty TypoCorrection). | |||
8441 | /// | |||
8442 | /// If we've failed to correct due to ambiguous corrections, we need to | |||
8443 | /// be sure to pass empty corrections and replacements. Otherwise it's | |||
8444 | /// possible that the Consumer has a TypoCorrection that failed to ambiguity | |||
8445 | /// and we don't want to report those diagnostics. | |||
8446 | void EmitAllDiagnostics(bool IsAmbiguous) { | |||
8447 | for (TypoExpr *TE : TypoExprs) { | |||
8448 | auto &State = SemaRef.getTypoExprState(TE); | |||
8449 | if (State.DiagHandler) { | |||
8450 | TypoCorrection TC = IsAmbiguous | |||
8451 | ? TypoCorrection() : State.Consumer->getCurrentCorrection(); | |||
8452 | ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE]; | |||
8453 | ||||
8454 | // Extract the NamedDecl from the transformed TypoExpr and add it to the | |||
8455 | // TypoCorrection, replacing the existing decls. This ensures the right | |||
8456 | // NamedDecl is used in diagnostics e.g. in the case where overload | |||
8457 | // resolution was used to select one from several possible decls that | |||
8458 | // had been stored in the TypoCorrection. | |||
8459 | if (auto *ND = getDeclFromExpr( | |||
8460 | Replacement.isInvalid() ? nullptr : Replacement.get())) | |||
8461 | TC.setCorrectionDecl(ND); | |||
8462 | ||||
8463 | State.DiagHandler(TC); | |||
8464 | } | |||
8465 | SemaRef.clearDelayedTypo(TE); | |||
8466 | } | |||
8467 | } | |||
8468 | ||||
8469 | /// Try to advance the typo correction state of the first unfinished TypoExpr. | |||
8470 | /// We allow advancement of the correction stream by removing it from the | |||
8471 | /// TransformCache which allows `TransformTypoExpr` to advance during the | |||
8472 | /// next transformation attempt. | |||
8473 | /// | |||
8474 | /// Any substitution attempts for the previous TypoExprs (which must have been | |||
8475 | /// finished) will need to be retried since it's possible that they will now | |||
8476 | /// be invalid given the latest advancement. | |||
8477 | /// | |||
8478 | /// We need to be sure that we're making progress - it's possible that the | |||
8479 | /// tree is so malformed that the transform never makes it to the | |||
8480 | /// `TransformTypoExpr`. | |||
8481 | /// | |||
8482 | /// Returns true if there are any untried correction combinations. | |||
8483 | bool CheckAndAdvanceTypoExprCorrectionStreams() { | |||
8484 | for (auto *TE : TypoExprs) { | |||
8485 | auto &State = SemaRef.getTypoExprState(TE); | |||
8486 | TransformCache.erase(TE); | |||
8487 | if (!State.Consumer->hasMadeAnyCorrectionProgress()) | |||
8488 | return false; | |||
8489 | if (!State.Consumer->finished()) | |||
8490 | return true; | |||
8491 | State.Consumer->resetCorrectionStream(); | |||
8492 | } | |||
8493 | return false; | |||
8494 | } | |||
8495 | ||||
8496 | NamedDecl *getDeclFromExpr(Expr *E) { | |||
8497 | if (auto *OE = dyn_cast_or_null<OverloadExpr>(E)) | |||
8498 | E = OverloadResolution[OE]; | |||
8499 | ||||
8500 | if (!E) | |||
8501 | return nullptr; | |||
8502 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) | |||
8503 | return DRE->getFoundDecl(); | |||
8504 | if (auto *ME = dyn_cast<MemberExpr>(E)) | |||
8505 | return ME->getFoundDecl(); | |||
8506 | // FIXME: Add any other expr types that could be seen by the delayed typo | |||
8507 | // correction TreeTransform for which the corresponding TypoCorrection could | |||
8508 | // contain multiple decls. | |||
8509 | return nullptr; | |||
8510 | } | |||
8511 | ||||
8512 | ExprResult TryTransform(Expr *E) { | |||
8513 | Sema::SFINAETrap Trap(SemaRef); | |||
8514 | ExprResult Res = TransformExpr(E); | |||
8515 | if (Trap.hasErrorOccurred() || Res.isInvalid()) | |||
8516 | return ExprError(); | |||
8517 | ||||
8518 | return ExprFilter(Res.get()); | |||
8519 | } | |||
8520 | ||||
8521 | // Since correcting typos may intoduce new TypoExprs, this function | |||
8522 | // checks for new TypoExprs and recurses if it finds any. Note that it will | |||
8523 | // only succeed if it is able to correct all typos in the given expression. | |||
8524 | ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) { | |||
8525 | if (Res.isInvalid()) { | |||
8526 | return Res; | |||
8527 | } | |||
8528 | // Check to see if any new TypoExprs were created. If so, we need to recurse | |||
8529 | // to check their validity. | |||
8530 | Expr *FixedExpr = Res.get(); | |||
8531 | ||||
8532 | auto SavedTypoExprs = std::move(TypoExprs); | |||
8533 | auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs); | |||
8534 | TypoExprs.clear(); | |||
8535 | AmbiguousTypoExprs.clear(); | |||
8536 | ||||
8537 | FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr); | |||
8538 | if (!TypoExprs.empty()) { | |||
8539 | // Recurse to handle newly created TypoExprs. If we're not able to | |||
8540 | // handle them, discard these TypoExprs. | |||
8541 | ExprResult RecurResult = | |||
8542 | RecursiveTransformLoop(FixedExpr, IsAmbiguous); | |||
8543 | if (RecurResult.isInvalid()) { | |||
8544 | Res = ExprError(); | |||
8545 | // Recursive corrections didn't work, wipe them away and don't add | |||
8546 | // them to the TypoExprs set. Remove them from Sema's TypoExpr list | |||
8547 | // since we don't want to clear them twice. Note: it's possible the | |||
8548 | // TypoExprs were created recursively and thus won't be in our | |||
8549 | // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`. | |||
8550 | auto &SemaTypoExprs = SemaRef.TypoExprs; | |||
8551 | for (auto *TE : TypoExprs) { | |||
8552 | TransformCache.erase(TE); | |||
8553 | SemaRef.clearDelayedTypo(TE); | |||
8554 | ||||
8555 | auto SI = find(SemaTypoExprs, TE); | |||
8556 | if (SI != SemaTypoExprs.end()) { | |||
8557 | SemaTypoExprs.erase(SI); | |||
8558 | } | |||
8559 | } | |||
8560 | } else { | |||
8561 | // TypoExpr is valid: add newly created TypoExprs since we were | |||
8562 | // able to correct them. | |||
8563 | Res = RecurResult; | |||
8564 | SavedTypoExprs.set_union(TypoExprs); | |||
8565 | } | |||
8566 | } | |||
8567 | ||||
8568 | TypoExprs = std::move(SavedTypoExprs); | |||
8569 | AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs); | |||
8570 | ||||
8571 | return Res; | |||
8572 | } | |||
8573 | ||||
8574 | // Try to transform the given expression, looping through the correction | |||
8575 | // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`. | |||
8576 | // | |||
8577 | // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to | |||
8578 | // true and this method immediately will return an `ExprError`. | |||
8579 | ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) { | |||
8580 | ExprResult Res; | |||
8581 | auto SavedTypoExprs = std::move(SemaRef.TypoExprs); | |||
8582 | SemaRef.TypoExprs.clear(); | |||
8583 | ||||
8584 | while (true) { | |||
8585 | Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); | |||
8586 | ||||
8587 | // Recursion encountered an ambiguous correction. This means that our | |||
8588 | // correction itself is ambiguous, so stop now. | |||
8589 | if (IsAmbiguous) | |||
8590 | break; | |||
8591 | ||||
8592 | // If the transform is still valid after checking for any new typos, | |||
8593 | // it's good to go. | |||
8594 | if (!Res.isInvalid()) | |||
8595 | break; | |||
8596 | ||||
8597 | // The transform was invalid, see if we have any TypoExprs with untried | |||
8598 | // correction candidates. | |||
8599 | if (!CheckAndAdvanceTypoExprCorrectionStreams()) | |||
8600 | break; | |||
8601 | } | |||
8602 | ||||
8603 | // If we found a valid result, double check to make sure it's not ambiguous. | |||
8604 | if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) { | |||
8605 | auto SavedTransformCache = | |||
8606 | llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache); | |||
8607 | ||||
8608 | // Ensure none of the TypoExprs have multiple typo correction candidates | |||
8609 | // with the same edit length that pass all the checks and filters. | |||
8610 | while (!AmbiguousTypoExprs.empty()) { | |||
8611 | auto TE = AmbiguousTypoExprs.back(); | |||
8612 | ||||
8613 | // TryTransform itself can create new Typos, adding them to the TypoExpr map | |||
8614 | // and invalidating our TypoExprState, so always fetch it instead of storing. | |||
8615 | SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition(); | |||
8616 | ||||
8617 | TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection(); | |||
8618 | TypoCorrection Next; | |||
8619 | do { | |||
8620 | // Fetch the next correction by erasing the typo from the cache and calling | |||
8621 | // `TryTransform` which will iterate through corrections in | |||
8622 | // `TransformTypoExpr`. | |||
8623 | TransformCache.erase(TE); | |||
8624 | ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); | |||
8625 | ||||
8626 | if (!AmbigRes.isInvalid() || IsAmbiguous) { | |||
8627 | SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream(); | |||
8628 | SavedTransformCache.erase(TE); | |||
8629 | Res = ExprError(); | |||
8630 | IsAmbiguous = true; | |||
8631 | break; | |||
8632 | } | |||
8633 | } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) && | |||
8634 | Next.getEditDistance(false) == TC.getEditDistance(false)); | |||
8635 | ||||
8636 | if (IsAmbiguous) | |||
8637 | break; | |||
8638 | ||||
8639 | AmbiguousTypoExprs.remove(TE); | |||
8640 | SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition(); | |||
8641 | TransformCache[TE] = SavedTransformCache[TE]; | |||
8642 | } | |||
8643 | TransformCache = std::move(SavedTransformCache); | |||
8644 | } | |||
8645 | ||||
8646 | // Wipe away any newly created TypoExprs that we don't know about. Since we | |||
8647 | // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only | |||
8648 | // possible if a `TypoExpr` is created during a transformation but then | |||
8649 | // fails before we can discover it. | |||
8650 | auto &SemaTypoExprs = SemaRef.TypoExprs; | |||
8651 | for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) { | |||
8652 | auto TE = *Iterator; | |||
8653 | auto FI = find(TypoExprs, TE); | |||
8654 | if (FI != TypoExprs.end()) { | |||
8655 | Iterator++; | |||
8656 | continue; | |||
8657 | } | |||
8658 | SemaRef.clearDelayedTypo(TE); | |||
8659 | Iterator = SemaTypoExprs.erase(Iterator); | |||
8660 | } | |||
8661 | SemaRef.TypoExprs = std::move(SavedTypoExprs); | |||
8662 | ||||
8663 | return Res; | |||
8664 | } | |||
8665 | ||||
8666 | public: | |||
8667 | TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter) | |||
8668 | : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {} | |||
8669 | ||||
8670 | ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc, | |||
8671 | MultiExprArg Args, | |||
8672 | SourceLocation RParenLoc, | |||
8673 | Expr *ExecConfig = nullptr) { | |||
8674 | auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args, | |||
8675 | RParenLoc, ExecConfig); | |||
8676 | if (auto *OE = dyn_cast<OverloadExpr>(Callee)) { | |||
8677 | if (Result.isUsable()) { | |||
8678 | Expr *ResultCall = Result.get(); | |||
8679 | if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall)) | |||
8680 | ResultCall = BE->getSubExpr(); | |||
8681 | if (auto *CE = dyn_cast<CallExpr>(ResultCall)) | |||
8682 | OverloadResolution[OE] = CE->getCallee(); | |||
8683 | } | |||
8684 | } | |||
8685 | return Result; | |||
8686 | } | |||
8687 | ||||
8688 | ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); } | |||
8689 | ||||
8690 | ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); } | |||
8691 | ||||
8692 | ExprResult Transform(Expr *E) { | |||
8693 | bool IsAmbiguous = false; | |||
8694 | ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous); | |||
8695 | ||||
8696 | if (!Res.isUsable()) | |||
8697 | FindTypoExprs(TypoExprs).TraverseStmt(E); | |||
8698 | ||||
8699 | EmitAllDiagnostics(IsAmbiguous); | |||
8700 | ||||
8701 | return Res; | |||
8702 | } | |||
8703 | ||||
8704 | ExprResult TransformTypoExpr(TypoExpr *E) { | |||
8705 | // If the TypoExpr hasn't been seen before, record it. Otherwise, return the | |||
8706 | // cached transformation result if there is one and the TypoExpr isn't the | |||
8707 | // first one that was encountered. | |||
8708 | auto &CacheEntry = TransformCache[E]; | |||
8709 | if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) { | |||
8710 | return CacheEntry; | |||
8711 | } | |||
8712 | ||||
8713 | auto &State = SemaRef.getTypoExprState(E); | |||
8714 | assert(State.Consumer && "Cannot transform a cleared TypoExpr")(static_cast <bool> (State.Consumer && "Cannot transform a cleared TypoExpr" ) ? void (0) : __assert_fail ("State.Consumer && \"Cannot transform a cleared TypoExpr\"" , "clang/lib/Sema/SemaExprCXX.cpp", 8714, __extension__ __PRETTY_FUNCTION__ )); | |||
8715 | ||||
8716 | // For the first TypoExpr and an uncached TypoExpr, find the next likely | |||
8717 | // typo correction and return it. | |||
8718 | while (TypoCorrection TC = State.Consumer->getNextCorrection()) { | |||
8719 | if (InitDecl && TC.getFoundDecl() == InitDecl) | |||
8720 | continue; | |||
8721 | // FIXME: If we would typo-correct to an invalid declaration, it's | |||
8722 | // probably best to just suppress all errors from this typo correction. | |||
8723 | ExprResult NE = State.RecoveryHandler ? | |||
8724 | State.RecoveryHandler(SemaRef, E, TC) : | |||
8725 | attemptRecovery(SemaRef, *State.Consumer, TC); | |||
8726 | if (!NE.isInvalid()) { | |||
8727 | // Check whether there may be a second viable correction with the same | |||
8728 | // edit distance; if so, remember this TypoExpr may have an ambiguous | |||
8729 | // correction so it can be more thoroughly vetted later. | |||
8730 | TypoCorrection Next; | |||
8731 | if ((Next = State.Consumer->peekNextCorrection()) && | |||
8732 | Next.getEditDistance(false) == TC.getEditDistance(false)) { | |||
8733 | AmbiguousTypoExprs.insert(E); | |||
8734 | } else { | |||
8735 | AmbiguousTypoExprs.remove(E); | |||
8736 | } | |||
8737 | assert(!NE.isUnset() &&(static_cast <bool> (!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult" ) ? void (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\"" , "clang/lib/Sema/SemaExprCXX.cpp", 8738, __extension__ __PRETTY_FUNCTION__ )) | |||
8738 | "Typo was transformed into a valid-but-null ExprResult")(static_cast <bool> (!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult" ) ? void (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\"" , "clang/lib/Sema/SemaExprCXX.cpp", 8738, __extension__ __PRETTY_FUNCTION__ )); | |||
8739 | return CacheEntry = NE; | |||
8740 | } | |||
8741 | } | |||
8742 | return CacheEntry = ExprError(); | |||
8743 | } | |||
8744 | }; | |||
8745 | } | |||
8746 | ||||
8747 | ExprResult | |||
8748 | Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, | |||
8749 | bool RecoverUncorrectedTypos, | |||
8750 | llvm::function_ref<ExprResult(Expr *)> Filter) { | |||
8751 | // If the current evaluation context indicates there are uncorrected typos | |||
8752 | // and the current expression isn't guaranteed to not have typos, try to | |||
8753 | // resolve any TypoExpr nodes that might be in the expression. | |||
8754 | if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos && | |||
8755 | (E->isTypeDependent() || E->isValueDependent() || | |||
8756 | E->isInstantiationDependent())) { | |||
8757 | auto TyposResolved = DelayedTypos.size(); | |||
8758 | auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E); | |||
8759 | TyposResolved -= DelayedTypos.size(); | |||
8760 | if (Result.isInvalid() || Result.get() != E) { | |||
8761 | ExprEvalContexts.back().NumTypos -= TyposResolved; | |||
8762 | if (Result.isInvalid() && RecoverUncorrectedTypos) { | |||
8763 | struct TyposReplace : TreeTransform<TyposReplace> { | |||
8764 | TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {} | |||
8765 | ExprResult TransformTypoExpr(clang::TypoExpr *E) { | |||
8766 | return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(), | |||
8767 | E->getEndLoc(), {}); | |||
8768 | } | |||
8769 | } TT(*this); | |||
8770 | return TT.TransformExpr(E); | |||
8771 | } | |||
8772 | return Result; | |||
8773 | } | |||
8774 | assert(TyposResolved == 0 && "Corrected typo but got same Expr back?")(static_cast <bool> (TyposResolved == 0 && "Corrected typo but got same Expr back?" ) ? void (0) : __assert_fail ("TyposResolved == 0 && \"Corrected typo but got same Expr back?\"" , "clang/lib/Sema/SemaExprCXX.cpp", 8774, __extension__ __PRETTY_FUNCTION__ )); | |||
8775 | } | |||
8776 | return E; | |||
8777 | } | |||
8778 | ||||
8779 | ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, | |||
8780 | bool DiscardedValue, bool IsConstexpr, | |||
8781 | bool IsTemplateArgument) { | |||
8782 | ExprResult FullExpr = FE; | |||
8783 | ||||
8784 | if (!FullExpr.get()) | |||
8785 | return ExprError(); | |||
8786 | ||||
8787 | if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get())) | |||
8788 | return ExprError(); | |||
8789 | ||||
8790 | if (DiscardedValue) { | |||
8791 | // Top-level expressions default to 'id' when we're in a debugger. | |||
8792 | if (getLangOpts().DebuggerCastResultToId && | |||
8793 | FullExpr.get()->getType() == Context.UnknownAnyTy) { | |||
8794 | FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType()); | |||
8795 | if (FullExpr.isInvalid()) | |||
8796 | return ExprError(); | |||
8797 | } | |||
8798 | ||||
8799 | FullExpr = CheckPlaceholderExpr(FullExpr.get()); | |||
8800 | if (FullExpr.isInvalid()) | |||
8801 | return ExprError(); | |||
8802 | ||||
8803 | FullExpr = IgnoredValueConversions(FullExpr.get()); | |||
8804 | if (FullExpr.isInvalid()) | |||
8805 | return ExprError(); | |||
8806 | ||||
8807 | DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr); | |||
8808 | } | |||
8809 | ||||
8810 | FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr, | |||
8811 | /*RecoverUncorrectedTypos=*/true); | |||
8812 | if (FullExpr.isInvalid()) | |||
8813 | return ExprError(); | |||
8814 | ||||
8815 | CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); | |||
8816 | ||||
8817 | // At the end of this full expression (which could be a deeply nested | |||
8818 | // lambda), if there is a potential capture within the nested lambda, | |||
8819 | // have the outer capture-able lambda try and capture it. | |||
8820 | // Consider the following code: | |||
8821 | // void f(int, int); | |||
8822 | // void f(const int&, double); | |||
8823 | // void foo() { | |||
8824 | // const int x = 10, y = 20; | |||
8825 | // auto L = [=](auto a) { | |||
8826 | // auto M = [=](auto b) { | |||
8827 | // f(x, b); <-- requires x to be captured by L and M | |||
8828 | // f(y, a); <-- requires y to be captured by L, but not all Ms | |||
8829 | // }; | |||
8830 | // }; | |||
8831 | // } | |||
8832 | ||||
8833 | // FIXME: Also consider what happens for something like this that involves | |||
8834 | // the gnu-extension statement-expressions or even lambda-init-captures: | |||
8835 | // void f() { | |||
8836 | // const int n = 0; | |||
8837 | // auto L = [&](auto a) { | |||
8838 | // +n + ({ 0; a; }); | |||
8839 | // }; | |||
8840 | // } | |||
8841 | // | |||
8842 | // Here, we see +n, and then the full-expression 0; ends, so we don't | |||
8843 | // capture n (and instead remove it from our list of potential captures), | |||
8844 | // and then the full-expression +n + ({ 0; }); ends, but it's too late | |||
8845 | // for us to see that we need to capture n after all. | |||
8846 | ||||
8847 | LambdaScopeInfo *const CurrentLSI = | |||
8848 | getCurLambda(/*IgnoreCapturedRegions=*/true); | |||
8849 | // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer | |||
8850 | // even if CurContext is not a lambda call operator. Refer to that Bug Report | |||
8851 | // for an example of the code that might cause this asynchrony. | |||
8852 | // By ensuring we are in the context of a lambda's call operator | |||
8853 | // we can fix the bug (we only need to check whether we need to capture | |||
8854 | // if we are within a lambda's body); but per the comments in that | |||
8855 | // PR, a proper fix would entail : | |||
8856 | // "Alternative suggestion: | |||
8857 | // - Add to Sema an integer holding the smallest (outermost) scope | |||
8858 | // index that we are *lexically* within, and save/restore/set to | |||
8859 | // FunctionScopes.size() in InstantiatingTemplate's | |||
8860 | // constructor/destructor. | |||
8861 | // - Teach the handful of places that iterate over FunctionScopes to | |||
8862 | // stop at the outermost enclosing lexical scope." | |||
8863 | DeclContext *DC = CurContext; | |||
8864 | while (DC && isa<CapturedDecl>(DC)) | |||
8865 | DC = DC->getParent(); | |||
8866 | const bool IsInLambdaDeclContext = isLambdaCallOperator(DC); | |||
8867 | if (IsInLambdaDeclContext && CurrentLSI && | |||
8868 | CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) | |||
8869 | CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, | |||
8870 | *this); | |||
8871 | return MaybeCreateExprWithCleanups(FullExpr); | |||
8872 | } | |||
8873 | ||||
8874 | StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { | |||
8875 | if (!FullStmt) return StmtError(); | |||
8876 | ||||
8877 | return MaybeCreateStmtWithCleanups(FullStmt); | |||
8878 | } | |||
8879 | ||||
8880 | Sema::IfExistsResult | |||
8881 | Sema::CheckMicrosoftIfExistsSymbol(Scope *S, | |||
8882 | CXXScopeSpec &SS, | |||
8883 | const DeclarationNameInfo &TargetNameInfo) { | |||
8884 | DeclarationName TargetName = TargetNameInfo.getName(); | |||
8885 | if (!TargetName) | |||
8886 | return IER_DoesNotExist; | |||
8887 | ||||
8888 | // If the name itself is dependent, then the result is dependent. | |||
8889 | if (TargetName.isDependentName()) | |||
8890 | return IER_Dependent; | |||
8891 | ||||
8892 | // Do the redeclaration lookup in the current scope. | |||
8893 | LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, | |||
8894 | Sema::NotForRedeclaration); | |||
8895 | LookupParsedName(R, S, &SS); | |||
8896 | R.suppressDiagnostics(); | |||
8897 | ||||
8898 | switch (R.getResultKind()) { | |||
8899 | case LookupResult::Found: | |||
8900 | case LookupResult::FoundOverloaded: | |||
8901 | case LookupResult::FoundUnresolvedValue: | |||
8902 | case LookupResult::Ambiguous: | |||
8903 | return IER_Exists; | |||
8904 | ||||
8905 | case LookupResult::NotFound: | |||
8906 | return IER_DoesNotExist; | |||
8907 | ||||
8908 | case LookupResult::NotFoundInCurrentInstantiation: | |||
8909 | return IER_Dependent; | |||
8910 | } | |||
8911 | ||||
8912 | llvm_unreachable("Invalid LookupResult Kind!")::llvm::llvm_unreachable_internal("Invalid LookupResult Kind!" , "clang/lib/Sema/SemaExprCXX.cpp", 8912); | |||
8913 | } | |||
8914 | ||||
8915 | Sema::IfExistsResult | |||
8916 | Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, | |||
8917 | bool IsIfExists, CXXScopeSpec &SS, | |||
8918 | UnqualifiedId &Name) { | |||
8919 | DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); | |||
8920 | ||||
8921 | // Check for an unexpanded parameter pack. | |||
8922 | auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists; | |||
8923 | if (DiagnoseUnexpandedParameterPack(SS, UPPC) || | |||
8924 | DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC)) | |||
8925 | return IER_Error; | |||
8926 | ||||
8927 | return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); | |||
8928 | } | |||
8929 | ||||
8930 | concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) { | |||
8931 | return BuildExprRequirement(E, /*IsSimple=*/true, | |||
8932 | /*NoexceptLoc=*/SourceLocation(), | |||
8933 | /*ReturnTypeRequirement=*/{}); | |||
8934 | } | |||
8935 | ||||
8936 | concepts::Requirement * | |||
8937 | Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, | |||
8938 | SourceLocation NameLoc, IdentifierInfo *TypeName, | |||
8939 | TemplateIdAnnotation *TemplateId) { | |||
8940 | assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&(static_cast <bool> (((!TypeName && TemplateId) || (TypeName && !TemplateId)) && "Exactly one of TypeName and TemplateId must be specified." ) ? void (0) : __assert_fail ("((!TypeName && TemplateId) || (TypeName && !TemplateId)) && \"Exactly one of TypeName and TemplateId must be specified.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 8941, __extension__ __PRETTY_FUNCTION__ )) | |||
8941 | "Exactly one of TypeName and TemplateId must be specified.")(static_cast <bool> (((!TypeName && TemplateId) || (TypeName && !TemplateId)) && "Exactly one of TypeName and TemplateId must be specified." ) ? void (0) : __assert_fail ("((!TypeName && TemplateId) || (TypeName && !TemplateId)) && \"Exactly one of TypeName and TemplateId must be specified.\"" , "clang/lib/Sema/SemaExprCXX.cpp", 8941, __extension__ __PRETTY_FUNCTION__ )); | |||
8942 | TypeSourceInfo *TSI = nullptr; | |||
8943 | if (TypeName) { | |||
8944 | QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc, | |||
8945 | SS.getWithLocInContext(Context), *TypeName, | |||
8946 | NameLoc, &TSI, /*DeducedTSTContext=*/false); | |||
8947 | if (T.isNull()) | |||
8948 | return nullptr; | |||
8949 | } else { | |||
8950 | ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(), | |||
8951 | TemplateId->NumArgs); | |||
8952 | TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS, | |||
8953 | TemplateId->TemplateKWLoc, | |||
8954 | TemplateId->Template, TemplateId->Name, | |||
8955 | TemplateId->TemplateNameLoc, | |||
8956 | TemplateId->LAngleLoc, ArgsPtr, | |||
8957 | TemplateId->RAngleLoc); | |||
8958 | if (T.isInvalid()) | |||
8959 | return nullptr; | |||
8960 | if (GetTypeFromParser(T.get(), &TSI).isNull()) | |||
8961 | return nullptr; | |||
8962 | } | |||
8963 | return BuildTypeRequirement(TSI); | |||
8964 | } | |||
8965 | ||||
8966 | concepts::Requirement * | |||
8967 | Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) { | |||
8968 | return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, | |||
8969 | /*ReturnTypeRequirement=*/{}); | |||
8970 | } | |||
8971 | ||||
8972 | concepts::Requirement * | |||
8973 | Sema::ActOnCompoundRequirement( | |||
8974 | Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, | |||
8975 | TemplateIdAnnotation *TypeConstraint, unsigned Depth) { | |||
8976 | // C++2a [expr.prim.req.compound] p1.3.3 | |||
8977 | // [..] the expression is deduced against an invented function template | |||
8978 | // F [...] F is a void function template with a single type template | |||
8979 | // parameter T declared with the constrained-parameter. Form a new | |||
8980 | // cv-qualifier-seq cv by taking the union of const and volatile specifiers | |||
8981 | // around the constrained-parameter. F has a single parameter whose | |||
8982 | // type-specifier is cv T followed by the abstract-declarator. [...] | |||
8983 | // | |||
8984 | // The cv part is done in the calling function - we get the concept with | |||
8985 | // arguments and the abstract declarator with the correct CV qualification and | |||
8986 | // have to synthesize T and the single parameter of F. | |||
8987 | auto &II = Context.Idents.get("expr-type"); | |||
8988 | auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext, | |||
8989 | SourceLocation(), | |||
8990 | SourceLocation(), Depth, | |||
8991 | /*Index=*/0, &II, | |||
8992 | /*Typename=*/true, | |||
8993 | /*ParameterPack=*/false, | |||
8994 | /*HasTypeConstraint=*/true); | |||
8995 | ||||
8996 | if (BuildTypeConstraint(SS, TypeConstraint, TParam, | |||
8997 | /*EllipsisLoc=*/SourceLocation(), | |||
8998 | /*AllowUnexpandedPack=*/true)) | |||
8999 | // Just produce a requirement with no type requirements. | |||
9000 | return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {}); | |||
9001 | ||||
9002 | auto *TPL = TemplateParameterList::Create(Context, SourceLocation(), | |||
9003 | SourceLocation(), | |||
9004 | ArrayRef<NamedDecl *>(TParam), | |||
9005 | SourceLocation(), | |||
9006 | /*RequiresClause=*/nullptr); | |||
9007 | return BuildExprRequirement( | |||
9008 | E, /*IsSimple=*/false, NoexceptLoc, | |||
9009 | concepts::ExprRequirement::ReturnTypeRequirement(TPL)); | |||
9010 | } | |||
9011 | ||||
9012 | concepts::ExprRequirement * | |||
9013 | Sema::BuildExprRequirement( | |||
9014 | Expr *E, bool IsSimple, SourceLocation NoexceptLoc, | |||
9015 | concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { | |||
9016 | auto Status = concepts::ExprRequirement::SS_Satisfied; | |||
9017 | ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; | |||
9018 | if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent()) | |||
9019 | Status = concepts::ExprRequirement::SS_Dependent; | |||
9020 | else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can) | |||
9021 | Status = concepts::ExprRequirement::SS_NoexceptNotMet; | |||
9022 | else if (ReturnTypeRequirement.isSubstitutionFailure()) | |||
9023 | Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure; | |||
9024 | else if (ReturnTypeRequirement.isTypeConstraint()) { | |||
9025 | // C++2a [expr.prim.req]p1.3.3 | |||
9026 | // The immediately-declared constraint ([temp]) of decltype((E)) shall | |||
9027 | // be satisfied. | |||
9028 | TemplateParameterList *TPL = | |||
9029 | ReturnTypeRequirement.getTypeConstraintTemplateParameterList(); | |||
9030 | QualType MatchedType = Context.getReferenceQualifiedType(E); | |||
9031 | llvm::SmallVector<TemplateArgument, 1> Args; | |||
9032 | Args.push_back(TemplateArgument(MatchedType)); | |||
9033 | ||||
9034 | auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0)); | |||
9035 | ||||
9036 | TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args); | |||
9037 | MultiLevelTemplateArgumentList MLTAL(Param, TAL.asArray(), | |||
9038 | /*Final=*/true); | |||
9039 | MLTAL.addOuterRetainedLevels(TPL->getDepth()); | |||
9040 | Expr *IDC = Param->getTypeConstraint()->getImmediatelyDeclaredConstraint(); | |||
9041 | ExprResult Constraint = SubstExpr(IDC, MLTAL); | |||
9042 | if (Constraint.isInvalid()) { | |||
9043 | Status = concepts::ExprRequirement::SS_ExprSubstitutionFailure; | |||
9044 | } else { | |||
9045 | SubstitutedConstraintExpr = | |||
9046 | cast<ConceptSpecializationExpr>(Constraint.get()); | |||
9047 | if (!SubstitutedConstraintExpr->isSatisfied()) | |||
9048 | Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied; | |||
9049 | } | |||
9050 | } | |||
9051 | return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc, | |||
9052 | ReturnTypeRequirement, Status, | |||
9053 | SubstitutedConstraintExpr); | |||
9054 | } | |||
9055 | ||||
9056 | concepts::ExprRequirement * | |||
9057 | Sema::BuildExprRequirement( | |||
9058 | concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic, | |||
9059 | bool IsSimple, SourceLocation NoexceptLoc, | |||
9060 | concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { | |||
9061 | return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic, | |||
9062 | IsSimple, NoexceptLoc, | |||
9063 | ReturnTypeRequirement); | |||
9064 | } | |||
9065 | ||||
9066 | concepts::TypeRequirement * | |||
9067 | Sema::BuildTypeRequirement(TypeSourceInfo *Type) { | |||
9068 | return new (Context) concepts::TypeRequirement(Type); | |||
9069 | } | |||
9070 | ||||
9071 | concepts::TypeRequirement * | |||
9072 | Sema::BuildTypeRequirement( | |||
9073 | concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { | |||
9074 | return new (Context) concepts::TypeRequirement(SubstDiag); | |||
9075 | } | |||
9076 | ||||
9077 | concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) { | |||
9078 | return BuildNestedRequirement(Constraint); | |||
9079 | } | |||
9080 | ||||
9081 | concepts::NestedRequirement * | |||
9082 | Sema::BuildNestedRequirement(Expr *Constraint) { | |||
9083 | ConstraintSatisfaction Satisfaction; | |||
9084 | if (!Constraint->isInstantiationDependent() && | |||
9085 | CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{}, | |||
9086 | Constraint->getSourceRange(), Satisfaction)) | |||
9087 | return nullptr; | |||
9088 | return new (Context) concepts::NestedRequirement(Context, Constraint, | |||
9089 | Satisfaction); | |||
9090 | } | |||
9091 | ||||
9092 | concepts::NestedRequirement * | |||
9093 | Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity, | |||
9094 | const ASTConstraintSatisfaction &Satisfaction) { | |||
9095 | return new (Context) concepts::NestedRequirement( | |||
9096 | InvalidConstraintEntity, | |||
9097 | ASTConstraintSatisfaction::Rebuild(Context, Satisfaction)); | |||
9098 | } | |||
9099 | ||||
9100 | RequiresExprBodyDecl * | |||
9101 | Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, | |||
9102 | ArrayRef<ParmVarDecl *> LocalParameters, | |||
9103 | Scope *BodyScope) { | |||
9104 | assert(BodyScope)(static_cast <bool> (BodyScope) ? void (0) : __assert_fail ("BodyScope", "clang/lib/Sema/SemaExprCXX.cpp", 9104, __extension__ __PRETTY_FUNCTION__)); | |||
9105 | ||||
9106 | RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext, | |||
9107 | RequiresKWLoc); | |||
9108 | ||||
9109 | PushDeclContext(BodyScope, Body); | |||
9110 | ||||
9111 | for (ParmVarDecl *Param : LocalParameters) { | |||
9112 | if (Param->hasDefaultArg()) | |||
9113 | // C++2a [expr.prim.req] p4 | |||
9114 | // [...] A local parameter of a requires-expression shall not have a | |||
9115 | // default argument. [...] | |||
9116 | Diag(Param->getDefaultArgRange().getBegin(), | |||
9117 | diag::err_requires_expr_local_parameter_default_argument); | |||
9118 | // Ignore default argument and move on | |||
9119 | ||||
9120 | Param->setDeclContext(Body); | |||
9121 | // If this has an identifier, add it to the scope stack. | |||
9122 | if (Param->getIdentifier()) { | |||
9123 | CheckShadow(BodyScope, Param); | |||
9124 | PushOnScopeChains(Param, BodyScope); | |||
9125 | } | |||
9126 | } | |||
9127 | return Body; | |||
9128 | } | |||
9129 | ||||
9130 | void Sema::ActOnFinishRequiresExpr() { | |||
9131 | assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!" ) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "clang/lib/Sema/SemaExprCXX.cpp", 9131, __extension__ __PRETTY_FUNCTION__ )); | |||
9132 | CurContext = CurContext->getLexicalParent(); | |||
9133 | assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!" ) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "clang/lib/Sema/SemaExprCXX.cpp", 9133, __extension__ __PRETTY_FUNCTION__ )); | |||
9134 | } | |||
9135 | ||||
9136 | ExprResult | |||
9137 | Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc, | |||
9138 | RequiresExprBodyDecl *Body, | |||
9139 | ArrayRef<ParmVarDecl *> LocalParameters, | |||
9140 | ArrayRef<concepts::Requirement *> Requirements, | |||
9141 | SourceLocation ClosingBraceLoc) { | |||
9142 | auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters, | |||
9143 | Requirements, ClosingBraceLoc); | |||
9144 | if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE)) | |||
9145 | return ExprError(); | |||
9146 | return RE; | |||
9147 | } |