1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// Implements semantic analysis for C++ expressions.
11 ///
12 //===----------------------------------------------------------------------===//
13
14 #include "TreeTransform.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/TypeLoc.h"
25 #include "clang/Basic/AlignedAllocation.h"
26 #include "clang/Basic/DiagnosticSema.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Basic/TypeTraits.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/DeclSpec.h"
32 #include "clang/Sema/Initialization.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/SemaInternal.h"
38 #include "clang/Sema/SemaLambda.h"
39 #include "clang/Sema/Template.h"
40 #include "clang/Sema/TemplateDeduction.h"
41 #include "llvm/ADT/APInt.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/TypeSize.h"
45 using namespace clang;
46 using namespace sema;
47
48 /// Handle the result of the special case name lookup for inheriting
49 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
50 /// constructor names in member using declarations, even if 'X' is not the
51 /// name of the corresponding type.
getInheritingConstructorName(CXXScopeSpec & SS,SourceLocation NameLoc,IdentifierInfo & Name)52 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
53 SourceLocation NameLoc,
54 IdentifierInfo &Name) {
55 NestedNameSpecifier *NNS = SS.getScopeRep();
56
57 // Convert the nested-name-specifier into a type.
58 QualType Type;
59 switch (NNS->getKind()) {
60 case NestedNameSpecifier::TypeSpec:
61 case NestedNameSpecifier::TypeSpecWithTemplate:
62 Type = QualType(NNS->getAsType(), 0);
63 break;
64
65 case NestedNameSpecifier::Identifier:
66 // Strip off the last layer of the nested-name-specifier and build a
67 // typename type for it.
68 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
69 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
70 NNS->getAsIdentifier());
71 break;
72
73 case NestedNameSpecifier::Global:
74 case NestedNameSpecifier::Super:
75 case NestedNameSpecifier::Namespace:
76 case NestedNameSpecifier::NamespaceAlias:
77 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
78 }
79
80 // This reference to the type is located entirely at the location of the
81 // final identifier in the qualified-id.
82 return CreateParsedType(Type,
83 Context.getTrivialTypeSourceInfo(Type, NameLoc));
84 }
85
getConstructorName(IdentifierInfo & II,SourceLocation NameLoc,Scope * S,CXXScopeSpec & SS,bool EnteringContext)86 ParsedType Sema::getConstructorName(IdentifierInfo &II,
87 SourceLocation NameLoc,
88 Scope *S, CXXScopeSpec &SS,
89 bool EnteringContext) {
90 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
91 assert(CurClass && &II == CurClass->getIdentifier() &&
92 "not a constructor name");
93
94 // When naming a constructor as a member of a dependent context (eg, in a
95 // friend declaration or an inherited constructor declaration), form an
96 // unresolved "typename" type.
97 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
98 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
99 return ParsedType::make(T);
100 }
101
102 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
103 return ParsedType();
104
105 // Find the injected-class-name declaration. Note that we make no attempt to
106 // diagnose cases where the injected-class-name is shadowed: the only
107 // declaration that can validly shadow the injected-class-name is a
108 // non-static data member, and if the class contains both a non-static data
109 // member and a constructor then it is ill-formed (we check that in
110 // CheckCompletedCXXClass).
111 CXXRecordDecl *InjectedClassName = nullptr;
112 for (NamedDecl *ND : CurClass->lookup(&II)) {
113 auto *RD = dyn_cast<CXXRecordDecl>(ND);
114 if (RD && RD->isInjectedClassName()) {
115 InjectedClassName = RD;
116 break;
117 }
118 }
119 if (!InjectedClassName) {
120 if (!CurClass->isInvalidDecl()) {
121 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
122 // properly. Work around it here for now.
123 Diag(SS.getLastQualifierNameLoc(),
124 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
125 }
126 return ParsedType();
127 }
128
129 QualType T = Context.getTypeDeclType(InjectedClassName);
130 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
131 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
132
133 return ParsedType::make(T);
134 }
135
getDestructorName(SourceLocation TildeLoc,IdentifierInfo & II,SourceLocation NameLoc,Scope * S,CXXScopeSpec & SS,ParsedType ObjectTypePtr,bool EnteringContext)136 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
137 IdentifierInfo &II,
138 SourceLocation NameLoc,
139 Scope *S, CXXScopeSpec &SS,
140 ParsedType ObjectTypePtr,
141 bool EnteringContext) {
142 // Determine where to perform name lookup.
143
144 // FIXME: This area of the standard is very messy, and the current
145 // wording is rather unclear about which scopes we search for the
146 // destructor name; see core issues 399 and 555. Issue 399 in
147 // particular shows where the current description of destructor name
148 // lookup is completely out of line with existing practice, e.g.,
149 // this appears to be ill-formed:
150 //
151 // namespace N {
152 // template <typename T> struct S {
153 // ~S();
154 // };
155 // }
156 //
157 // void f(N::S<int>* s) {
158 // s->N::S<int>::~S();
159 // }
160 //
161 // See also PR6358 and PR6359.
162 //
163 // For now, we accept all the cases in which the name given could plausibly
164 // be interpreted as a correct destructor name, issuing off-by-default
165 // extension diagnostics on the cases that don't strictly conform to the
166 // C++20 rules. This basically means we always consider looking in the
167 // nested-name-specifier prefix, the complete nested-name-specifier, and
168 // the scope, and accept if we find the expected type in any of the three
169 // places.
170
171 if (SS.isInvalid())
172 return nullptr;
173
174 // Whether we've failed with a diagnostic already.
175 bool Failed = false;
176
177 llvm::SmallVector<NamedDecl*, 8> FoundDecls;
178 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
179
180 // If we have an object type, it's because we are in a
181 // pseudo-destructor-expression or a member access expression, and
182 // we know what type we're looking for.
183 QualType SearchType =
184 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
185
186 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
187 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
188 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
189 if (!Type)
190 return false;
191
192 if (SearchType.isNull() || SearchType->isDependentType())
193 return true;
194
195 QualType T = Context.getTypeDeclType(Type);
196 return Context.hasSameUnqualifiedType(T, SearchType);
197 };
198
199 unsigned NumAcceptableResults = 0;
200 for (NamedDecl *D : Found) {
201 if (IsAcceptableResult(D))
202 ++NumAcceptableResults;
203
204 // Don't list a class twice in the lookup failure diagnostic if it's
205 // found by both its injected-class-name and by the name in the enclosing
206 // scope.
207 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
208 if (RD->isInjectedClassName())
209 D = cast<NamedDecl>(RD->getParent());
210
211 if (FoundDeclSet.insert(D).second)
212 FoundDecls.push_back(D);
213 }
214
215 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
216 // results, and all non-matching results if we have a search type. It's not
217 // clear what the right behavior is if destructor lookup hits an ambiguity,
218 // but other compilers do generally accept at least some kinds of
219 // ambiguity.
220 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
221 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
222 LookupResult::Filter F = Found.makeFilter();
223 while (F.hasNext()) {
224 NamedDecl *D = F.next();
225 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
226 Diag(D->getLocation(), diag::note_destructor_type_here)
227 << Context.getTypeDeclType(TD);
228 else
229 Diag(D->getLocation(), diag::note_destructor_nontype_here);
230
231 if (!IsAcceptableResult(D))
232 F.erase();
233 }
234 F.done();
235 }
236
237 if (Found.isAmbiguous())
238 Failed = true;
239
240 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
241 if (IsAcceptableResult(Type)) {
242 QualType T = Context.getTypeDeclType(Type);
243 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
244 return CreateParsedType(T,
245 Context.getTrivialTypeSourceInfo(T, NameLoc));
246 }
247 }
248
249 return nullptr;
250 };
251
252 bool IsDependent = false;
253
254 auto LookupInObjectType = [&]() -> ParsedType {
255 if (Failed || SearchType.isNull())
256 return nullptr;
257
258 IsDependent |= SearchType->isDependentType();
259
260 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
261 DeclContext *LookupCtx = computeDeclContext(SearchType);
262 if (!LookupCtx)
263 return nullptr;
264 LookupQualifiedName(Found, LookupCtx);
265 return CheckLookupResult(Found);
266 };
267
268 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
269 if (Failed)
270 return nullptr;
271
272 IsDependent |= isDependentScopeSpecifier(LookupSS);
273 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
274 if (!LookupCtx)
275 return nullptr;
276
277 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
278 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
279 Failed = true;
280 return nullptr;
281 }
282 LookupQualifiedName(Found, LookupCtx);
283 return CheckLookupResult(Found);
284 };
285
286 auto LookupInScope = [&]() -> ParsedType {
287 if (Failed || !S)
288 return nullptr;
289
290 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
291 LookupName(Found, S);
292 return CheckLookupResult(Found);
293 };
294
295 // C++2a [basic.lookup.qual]p6:
296 // In a qualified-id of the form
297 //
298 // nested-name-specifier[opt] type-name :: ~ type-name
299 //
300 // the second type-name is looked up in the same scope as the first.
301 //
302 // We interpret this as meaning that if you do a dual-scope lookup for the
303 // first name, you also do a dual-scope lookup for the second name, per
304 // C++ [basic.lookup.classref]p4:
305 //
306 // If the id-expression in a class member access is a qualified-id of the
307 // form
308 //
309 // class-name-or-namespace-name :: ...
310 //
311 // the class-name-or-namespace-name following the . or -> is first looked
312 // up in the class of the object expression and the name, if found, is used.
313 // Otherwise, it is looked up in the context of the entire
314 // postfix-expression.
315 //
316 // This looks in the same scopes as for an unqualified destructor name:
317 //
318 // C++ [basic.lookup.classref]p3:
319 // If the unqualified-id is ~ type-name, the type-name is looked up
320 // in the context of the entire postfix-expression. If the type T
321 // of the object expression is of a class type C, the type-name is
322 // also looked up in the scope of class C. At least one of the
323 // lookups shall find a name that refers to cv T.
324 //
325 // FIXME: The intent is unclear here. Should type-name::~type-name look in
326 // the scope anyway if it finds a non-matching name declared in the class?
327 // If both lookups succeed and find a dependent result, which result should
328 // we retain? (Same question for p->~type-name().)
329
330 if (NestedNameSpecifier *Prefix =
331 SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
332 // This is
333 //
334 // nested-name-specifier type-name :: ~ type-name
335 //
336 // Look for the second type-name in the nested-name-specifier.
337 CXXScopeSpec PrefixSS;
338 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
339 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
340 return T;
341 } else {
342 // This is one of
343 //
344 // type-name :: ~ type-name
345 // ~ type-name
346 //
347 // Look in the scope and (if any) the object type.
348 if (ParsedType T = LookupInScope())
349 return T;
350 if (ParsedType T = LookupInObjectType())
351 return T;
352 }
353
354 if (Failed)
355 return nullptr;
356
357 if (IsDependent) {
358 // We didn't find our type, but that's OK: it's dependent anyway.
359
360 // FIXME: What if we have no nested-name-specifier?
361 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
362 SS.getWithLocInContext(Context),
363 II, NameLoc);
364 return ParsedType::make(T);
365 }
366
367 // The remaining cases are all non-standard extensions imitating the behavior
368 // of various other compilers.
369 unsigned NumNonExtensionDecls = FoundDecls.size();
370
371 if (SS.isSet()) {
372 // For compatibility with older broken C++ rules and existing code,
373 //
374 // nested-name-specifier :: ~ type-name
375 //
376 // also looks for type-name within the nested-name-specifier.
377 if (ParsedType T = LookupInNestedNameSpec(SS)) {
378 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
379 << SS.getRange()
380 << FixItHint::CreateInsertion(SS.getEndLoc(),
381 ("::" + II.getName()).str());
382 return T;
383 }
384
385 // For compatibility with other compilers and older versions of Clang,
386 //
387 // nested-name-specifier type-name :: ~ type-name
388 //
389 // also looks for type-name in the scope. Unfortunately, we can't
390 // reasonably apply this fallback for dependent nested-name-specifiers.
391 if (SS.getScopeRep()->getPrefix()) {
392 if (ParsedType T = LookupInScope()) {
393 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
394 << FixItHint::CreateRemoval(SS.getRange());
395 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
396 << GetTypeFromParser(T);
397 return T;
398 }
399 }
400 }
401
402 // We didn't find anything matching; tell the user what we did find (if
403 // anything).
404
405 // Don't tell the user about declarations we shouldn't have found.
406 FoundDecls.resize(NumNonExtensionDecls);
407
408 // List types before non-types.
409 std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
410 [](NamedDecl *A, NamedDecl *B) {
411 return isa<TypeDecl>(A->getUnderlyingDecl()) >
412 isa<TypeDecl>(B->getUnderlyingDecl());
413 });
414
415 // Suggest a fixit to properly name the destroyed type.
416 auto MakeFixItHint = [&]{
417 const CXXRecordDecl *Destroyed = nullptr;
418 // FIXME: If we have a scope specifier, suggest its last component?
419 if (!SearchType.isNull())
420 Destroyed = SearchType->getAsCXXRecordDecl();
421 else if (S)
422 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
423 if (Destroyed)
424 return FixItHint::CreateReplacement(SourceRange(NameLoc),
425 Destroyed->getNameAsString());
426 return FixItHint();
427 };
428
429 if (FoundDecls.empty()) {
430 // FIXME: Attempt typo-correction?
431 Diag(NameLoc, diag::err_undeclared_destructor_name)
432 << &II << MakeFixItHint();
433 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
434 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
435 assert(!SearchType.isNull() &&
436 "should only reject a type result if we have a search type");
437 QualType T = Context.getTypeDeclType(TD);
438 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
439 << T << SearchType << MakeFixItHint();
440 } else {
441 Diag(NameLoc, diag::err_destructor_expr_nontype)
442 << &II << MakeFixItHint();
443 }
444 } else {
445 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
446 : diag::err_destructor_expr_mismatch)
447 << &II << SearchType << MakeFixItHint();
448 }
449
450 for (NamedDecl *FoundD : FoundDecls) {
451 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
452 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
453 << Context.getTypeDeclType(TD);
454 else
455 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
456 << FoundD;
457 }
458
459 return nullptr;
460 }
461
getDestructorTypeForDecltype(const DeclSpec & DS,ParsedType ObjectType)462 ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
463 ParsedType ObjectType) {
464 if (DS.getTypeSpecType() == DeclSpec::TST_error)
465 return nullptr;
466
467 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
468 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
469 return nullptr;
470 }
471
472 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
473 "unexpected type in getDestructorType");
474 QualType T = BuildDecltypeType(DS.getRepAsExpr());
475
476 // If we know the type of the object, check that the correct destructor
477 // type was named now; we can give better diagnostics this way.
478 QualType SearchType = GetTypeFromParser(ObjectType);
479 if (!SearchType.isNull() && !SearchType->isDependentType() &&
480 !Context.hasSameUnqualifiedType(T, SearchType)) {
481 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
482 << T << SearchType;
483 return nullptr;
484 }
485
486 return ParsedType::make(T);
487 }
488
checkLiteralOperatorId(const CXXScopeSpec & SS,const UnqualifiedId & Name,bool IsUDSuffix)489 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
490 const UnqualifiedId &Name, bool IsUDSuffix) {
491 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
492 if (!IsUDSuffix) {
493 // [over.literal] p8
494 //
495 // double operator""_Bq(long double); // OK: not a reserved identifier
496 // double operator"" _Bq(long double); // ill-formed, no diagnostic required
497 IdentifierInfo *II = Name.Identifier;
498 ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts());
499 SourceLocation Loc = Name.getEndLoc();
500 if (isReservedInAllContexts(Status) &&
501 !PP.getSourceManager().isInSystemHeader(Loc)) {
502 Diag(Loc, diag::warn_reserved_extern_symbol)
503 << II << static_cast<int>(Status)
504 << FixItHint::CreateReplacement(
505 Name.getSourceRange(),
506 (StringRef("operator\"\"") + II->getName()).str());
507 }
508 }
509
510 if (!SS.isValid())
511 return false;
512
513 switch (SS.getScopeRep()->getKind()) {
514 case NestedNameSpecifier::Identifier:
515 case NestedNameSpecifier::TypeSpec:
516 case NestedNameSpecifier::TypeSpecWithTemplate:
517 // Per C++11 [over.literal]p2, literal operators can only be declared at
518 // namespace scope. Therefore, this unqualified-id cannot name anything.
519 // Reject it early, because we have no AST representation for this in the
520 // case where the scope is dependent.
521 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
522 << SS.getScopeRep();
523 return true;
524
525 case NestedNameSpecifier::Global:
526 case NestedNameSpecifier::Super:
527 case NestedNameSpecifier::Namespace:
528 case NestedNameSpecifier::NamespaceAlias:
529 return false;
530 }
531
532 llvm_unreachable("unknown nested name specifier kind");
533 }
534
535 /// Build a C++ typeid expression with a type operand.
BuildCXXTypeId(QualType TypeInfoType,SourceLocation TypeidLoc,TypeSourceInfo * Operand,SourceLocation RParenLoc)536 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
537 SourceLocation TypeidLoc,
538 TypeSourceInfo *Operand,
539 SourceLocation RParenLoc) {
540 // C++ [expr.typeid]p4:
541 // The top-level cv-qualifiers of the lvalue expression or the type-id
542 // that is the operand of typeid are always ignored.
543 // If the type of the type-id is a class type or a reference to a class
544 // type, the class shall be completely-defined.
545 Qualifiers Quals;
546 QualType T
547 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
548 Quals);
549 if (T->getAs<RecordType>() &&
550 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
551 return ExprError();
552
553 if (T->isVariablyModifiedType())
554 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
555
556 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
557 return ExprError();
558
559 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
560 SourceRange(TypeidLoc, RParenLoc));
561 }
562
563 /// Build a C++ typeid expression with an expression operand.
BuildCXXTypeId(QualType TypeInfoType,SourceLocation TypeidLoc,Expr * E,SourceLocation RParenLoc)564 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
565 SourceLocation TypeidLoc,
566 Expr *E,
567 SourceLocation RParenLoc) {
568 bool WasEvaluated = false;
569 if (E && !E->isTypeDependent()) {
570 if (E->hasPlaceholderType()) {
571 ExprResult result = CheckPlaceholderExpr(E);
572 if (result.isInvalid()) return ExprError();
573 E = result.get();
574 }
575
576 QualType T = E->getType();
577 if (const RecordType *RecordT = T->getAs<RecordType>()) {
578 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
579 // C++ [expr.typeid]p3:
580 // [...] If the type of the expression is a class type, the class
581 // shall be completely-defined.
582 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
583 return ExprError();
584
585 // C++ [expr.typeid]p3:
586 // When typeid is applied to an expression other than an glvalue of a
587 // polymorphic class type [...] [the] expression is an unevaluated
588 // operand. [...]
589 if (RecordD->isPolymorphic() && E->isGLValue()) {
590 if (isUnevaluatedContext()) {
591 // The operand was processed in unevaluated context, switch the
592 // context and recheck the subexpression.
593 ExprResult Result = TransformToPotentiallyEvaluated(E);
594 if (Result.isInvalid())
595 return ExprError();
596 E = Result.get();
597 }
598
599 // We require a vtable to query the type at run time.
600 MarkVTableUsed(TypeidLoc, RecordD);
601 WasEvaluated = true;
602 }
603 }
604
605 ExprResult Result = CheckUnevaluatedOperand(E);
606 if (Result.isInvalid())
607 return ExprError();
608 E = Result.get();
609
610 // C++ [expr.typeid]p4:
611 // [...] If the type of the type-id is a reference to a possibly
612 // cv-qualified type, the result of the typeid expression refers to a
613 // std::type_info object representing the cv-unqualified referenced
614 // type.
615 Qualifiers Quals;
616 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
617 if (!Context.hasSameType(T, UnqualT)) {
618 T = UnqualT;
619 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
620 }
621 }
622
623 if (E->getType()->isVariablyModifiedType())
624 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
625 << E->getType());
626 else if (!inTemplateInstantiation() &&
627 E->HasSideEffects(Context, WasEvaluated)) {
628 // The expression operand for typeid is in an unevaluated expression
629 // context, so side effects could result in unintended consequences.
630 Diag(E->getExprLoc(), WasEvaluated
631 ? diag::warn_side_effects_typeid
632 : diag::warn_side_effects_unevaluated_context);
633 }
634
635 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
636 SourceRange(TypeidLoc, RParenLoc));
637 }
638
639 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
640 ExprResult
ActOnCXXTypeid(SourceLocation OpLoc,SourceLocation LParenLoc,bool isType,void * TyOrExpr,SourceLocation RParenLoc)641 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
642 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
643 // typeid is not supported in OpenCL.
644 if (getLangOpts().OpenCLCPlusPlus) {
645 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
646 << "typeid");
647 }
648
649 // Find the std::type_info type.
650 if (!getStdNamespace())
651 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
652
653 if (!CXXTypeInfoDecl) {
654 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
655 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
656 LookupQualifiedName(R, getStdNamespace());
657 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
658 // Microsoft's typeinfo doesn't have type_info in std but in the global
659 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
660 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
661 LookupQualifiedName(R, Context.getTranslationUnitDecl());
662 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
663 }
664 if (!CXXTypeInfoDecl)
665 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
666 }
667
668 if (!getLangOpts().RTTI) {
669 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
670 }
671
672 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
673
674 if (isType) {
675 // The operand is a type; handle it as such.
676 TypeSourceInfo *TInfo = nullptr;
677 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
678 &TInfo);
679 if (T.isNull())
680 return ExprError();
681
682 if (!TInfo)
683 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
684
685 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
686 }
687
688 // The operand is an expression.
689 ExprResult Result =
690 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
691
692 if (!getLangOpts().RTTIData && !Result.isInvalid())
693 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
694 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
695 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
696 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
697 DiagnosticOptions::MSVC);
698 return Result;
699 }
700
701 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
702 /// a single GUID.
703 static void
getUuidAttrOfType(Sema & SemaRef,QualType QT,llvm::SmallSetVector<const UuidAttr *,1> & UuidAttrs)704 getUuidAttrOfType(Sema &SemaRef, QualType QT,
705 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
706 // Optionally remove one level of pointer, reference or array indirection.
707 const Type *Ty = QT.getTypePtr();
708 if (QT->isPointerType() || QT->isReferenceType())
709 Ty = QT->getPointeeType().getTypePtr();
710 else if (QT->isArrayType())
711 Ty = Ty->getBaseElementTypeUnsafe();
712
713 const auto *TD = Ty->getAsTagDecl();
714 if (!TD)
715 return;
716
717 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
718 UuidAttrs.insert(Uuid);
719 return;
720 }
721
722 // __uuidof can grab UUIDs from template arguments.
723 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
724 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
725 for (const TemplateArgument &TA : TAL.asArray()) {
726 const UuidAttr *UuidForTA = nullptr;
727 if (TA.getKind() == TemplateArgument::Type)
728 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
729 else if (TA.getKind() == TemplateArgument::Declaration)
730 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
731
732 if (UuidForTA)
733 UuidAttrs.insert(UuidForTA);
734 }
735 }
736 }
737
738 /// Build a Microsoft __uuidof expression with a type operand.
BuildCXXUuidof(QualType Type,SourceLocation TypeidLoc,TypeSourceInfo * Operand,SourceLocation RParenLoc)739 ExprResult Sema::BuildCXXUuidof(QualType Type,
740 SourceLocation TypeidLoc,
741 TypeSourceInfo *Operand,
742 SourceLocation RParenLoc) {
743 MSGuidDecl *Guid = nullptr;
744 if (!Operand->getType()->isDependentType()) {
745 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
746 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
747 if (UuidAttrs.empty())
748 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
749 if (UuidAttrs.size() > 1)
750 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
751 Guid = UuidAttrs.back()->getGuidDecl();
752 }
753
754 return new (Context)
755 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
756 }
757
758 /// Build a Microsoft __uuidof expression with an expression operand.
BuildCXXUuidof(QualType Type,SourceLocation TypeidLoc,Expr * E,SourceLocation RParenLoc)759 ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,
760 Expr *E, SourceLocation RParenLoc) {
761 MSGuidDecl *Guid = nullptr;
762 if (!E->getType()->isDependentType()) {
763 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
764 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
765 Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});
766 } else {
767 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
768 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
769 if (UuidAttrs.empty())
770 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
771 if (UuidAttrs.size() > 1)
772 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
773 Guid = UuidAttrs.back()->getGuidDecl();
774 }
775 }
776
777 return new (Context)
778 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
779 }
780
781 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
782 ExprResult
ActOnCXXUuidof(SourceLocation OpLoc,SourceLocation LParenLoc,bool isType,void * TyOrExpr,SourceLocation RParenLoc)783 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
784 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
785 QualType GuidType = Context.getMSGuidType();
786 GuidType.addConst();
787
788 if (isType) {
789 // The operand is a type; handle it as such.
790 TypeSourceInfo *TInfo = nullptr;
791 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
792 &TInfo);
793 if (T.isNull())
794 return ExprError();
795
796 if (!TInfo)
797 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
798
799 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
800 }
801
802 // The operand is an expression.
803 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
804 }
805
806 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
807 ExprResult
ActOnCXXBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)808 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
809 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
810 "Unknown C++ Boolean value!");
811 return new (Context)
812 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
813 }
814
815 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
816 ExprResult
ActOnCXXNullPtrLiteral(SourceLocation Loc)817 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
818 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
819 }
820
821 /// ActOnCXXThrow - Parse throw expressions.
822 ExprResult
ActOnCXXThrow(Scope * S,SourceLocation OpLoc,Expr * Ex)823 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
824 bool IsThrownVarInScope = false;
825 if (Ex) {
826 // C++0x [class.copymove]p31:
827 // When certain criteria are met, an implementation is allowed to omit the
828 // copy/move construction of a class object [...]
829 //
830 // - in a throw-expression, when the operand is the name of a
831 // non-volatile automatic object (other than a function or catch-
832 // clause parameter) whose scope does not extend beyond the end of the
833 // innermost enclosing try-block (if there is one), the copy/move
834 // operation from the operand to the exception object (15.1) can be
835 // omitted by constructing the automatic object directly into the
836 // exception object
837 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
838 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
839 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
840 for( ; S; S = S->getParent()) {
841 if (S->isDeclScope(Var)) {
842 IsThrownVarInScope = true;
843 break;
844 }
845
846 // FIXME: Many of the scope checks here seem incorrect.
847 if (S->getFlags() &
848 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
849 Scope::ObjCMethodScope | Scope::TryScope))
850 break;
851 }
852 }
853 }
854 }
855
856 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
857 }
858
BuildCXXThrow(SourceLocation OpLoc,Expr * Ex,bool IsThrownVarInScope)859 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
860 bool IsThrownVarInScope) {
861 // Don't report an error if 'throw' is used in system headers.
862 if (!getLangOpts().CXXExceptions &&
863 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
864 // Delay error emission for the OpenMP device code.
865 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
866 }
867
868 // Exceptions aren't allowed in CUDA device code.
869 if (getLangOpts().CUDA)
870 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
871 << "throw" << CurrentCUDATarget();
872
873 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
874 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
875
876 if (Ex && !Ex->isTypeDependent()) {
877 // Initialize the exception result. This implicitly weeds out
878 // abstract types or types with inaccessible copy constructors.
879
880 // C++0x [class.copymove]p31:
881 // When certain criteria are met, an implementation is allowed to omit the
882 // copy/move construction of a class object [...]
883 //
884 // - in a throw-expression, when the operand is the name of a
885 // non-volatile automatic object (other than a function or
886 // catch-clause
887 // parameter) whose scope does not extend beyond the end of the
888 // innermost enclosing try-block (if there is one), the copy/move
889 // operation from the operand to the exception object (15.1) can be
890 // omitted by constructing the automatic object directly into the
891 // exception object
892 NamedReturnInfo NRInfo =
893 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
894
895 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
896 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
897 return ExprError();
898
899 InitializedEntity Entity =
900 InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
901 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
902 if (Res.isInvalid())
903 return ExprError();
904 Ex = Res.get();
905 }
906
907 // PPC MMA non-pointer types are not allowed as throw expr types.
908 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
909 CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
910
911 return new (Context)
912 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
913 }
914
915 static void
collectPublicBases(CXXRecordDecl * RD,llvm::DenseMap<CXXRecordDecl *,unsigned> & SubobjectsSeen,llvm::SmallPtrSetImpl<CXXRecordDecl * > & VBases,llvm::SetVector<CXXRecordDecl * > & PublicSubobjectsSeen,bool ParentIsPublic)916 collectPublicBases(CXXRecordDecl *RD,
917 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
918 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
919 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
920 bool ParentIsPublic) {
921 for (const CXXBaseSpecifier &BS : RD->bases()) {
922 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
923 bool NewSubobject;
924 // Virtual bases constitute the same subobject. Non-virtual bases are
925 // always distinct subobjects.
926 if (BS.isVirtual())
927 NewSubobject = VBases.insert(BaseDecl).second;
928 else
929 NewSubobject = true;
930
931 if (NewSubobject)
932 ++SubobjectsSeen[BaseDecl];
933
934 // Only add subobjects which have public access throughout the entire chain.
935 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
936 if (PublicPath)
937 PublicSubobjectsSeen.insert(BaseDecl);
938
939 // Recurse on to each base subobject.
940 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
941 PublicPath);
942 }
943 }
944
getUnambiguousPublicSubobjects(CXXRecordDecl * RD,llvm::SmallVectorImpl<CXXRecordDecl * > & Objects)945 static void getUnambiguousPublicSubobjects(
946 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
947 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
948 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
949 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
950 SubobjectsSeen[RD] = 1;
951 PublicSubobjectsSeen.insert(RD);
952 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
953 /*ParentIsPublic=*/true);
954
955 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
956 // Skip ambiguous objects.
957 if (SubobjectsSeen[PublicSubobject] > 1)
958 continue;
959
960 Objects.push_back(PublicSubobject);
961 }
962 }
963
964 /// CheckCXXThrowOperand - Validate the operand of a throw.
CheckCXXThrowOperand(SourceLocation ThrowLoc,QualType ExceptionObjectTy,Expr * E)965 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
966 QualType ExceptionObjectTy, Expr *E) {
967 // If the type of the exception would be an incomplete type or a pointer
968 // to an incomplete type other than (cv) void the program is ill-formed.
969 QualType Ty = ExceptionObjectTy;
970 bool isPointer = false;
971 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
972 Ty = Ptr->getPointeeType();
973 isPointer = true;
974 }
975 if (!isPointer || !Ty->isVoidType()) {
976 if (RequireCompleteType(ThrowLoc, Ty,
977 isPointer ? diag::err_throw_incomplete_ptr
978 : diag::err_throw_incomplete,
979 E->getSourceRange()))
980 return true;
981
982 if (!isPointer && Ty->isSizelessType()) {
983 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
984 return true;
985 }
986
987 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
988 diag::err_throw_abstract_type, E))
989 return true;
990 }
991
992 // If the exception has class type, we need additional handling.
993 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
994 if (!RD)
995 return false;
996
997 // If we are throwing a polymorphic class type or pointer thereof,
998 // exception handling will make use of the vtable.
999 MarkVTableUsed(ThrowLoc, RD);
1000
1001 // If a pointer is thrown, the referenced object will not be destroyed.
1002 if (isPointer)
1003 return false;
1004
1005 // If the class has a destructor, we must be able to call it.
1006 if (!RD->hasIrrelevantDestructor()) {
1007 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
1008 MarkFunctionReferenced(E->getExprLoc(), Destructor);
1009 CheckDestructorAccess(E->getExprLoc(), Destructor,
1010 PDiag(diag::err_access_dtor_exception) << Ty);
1011 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
1012 return true;
1013 }
1014 }
1015
1016 // The MSVC ABI creates a list of all types which can catch the exception
1017 // object. This list also references the appropriate copy constructor to call
1018 // if the object is caught by value and has a non-trivial copy constructor.
1019 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1020 // We are only interested in the public, unambiguous bases contained within
1021 // the exception object. Bases which are ambiguous or otherwise
1022 // inaccessible are not catchable types.
1023 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1024 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1025
1026 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1027 // Attempt to lookup the copy constructor. Various pieces of machinery
1028 // will spring into action, like template instantiation, which means this
1029 // cannot be a simple walk of the class's decls. Instead, we must perform
1030 // lookup and overload resolution.
1031 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1032 if (!CD || CD->isDeleted())
1033 continue;
1034
1035 // Mark the constructor referenced as it is used by this throw expression.
1036 MarkFunctionReferenced(E->getExprLoc(), CD);
1037
1038 // Skip this copy constructor if it is trivial, we don't need to record it
1039 // in the catchable type data.
1040 if (CD->isTrivial())
1041 continue;
1042
1043 // The copy constructor is non-trivial, create a mapping from this class
1044 // type to this constructor.
1045 // N.B. The selection of copy constructor is not sensitive to this
1046 // particular throw-site. Lookup will be performed at the catch-site to
1047 // ensure that the copy constructor is, in fact, accessible (via
1048 // friendship or any other means).
1049 Context.addCopyConstructorForExceptionObject(Subobject, CD);
1050
1051 // We don't keep the instantiated default argument expressions around so
1052 // we must rebuild them here.
1053 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1054 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1055 return true;
1056 }
1057 }
1058 }
1059
1060 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1061 // the runtime with no ability for the compiler to request additional
1062 // alignment. Warn if the exception type requires alignment beyond the minimum
1063 // guaranteed by the target C++ runtime.
1064 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1065 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1066 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1067 if (ExnObjAlign < TypeAlign) {
1068 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1069 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1070 << Ty << (unsigned)TypeAlign.getQuantity()
1071 << (unsigned)ExnObjAlign.getQuantity();
1072 }
1073 }
1074
1075 return false;
1076 }
1077
adjustCVQualifiersForCXXThisWithinLambda(ArrayRef<FunctionScopeInfo * > FunctionScopes,QualType ThisTy,DeclContext * CurSemaContext,ASTContext & ASTCtx)1078 static QualType adjustCVQualifiersForCXXThisWithinLambda(
1079 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1080 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1081
1082 QualType ClassType = ThisTy->getPointeeType();
1083 LambdaScopeInfo *CurLSI = nullptr;
1084 DeclContext *CurDC = CurSemaContext;
1085
1086 // Iterate through the stack of lambdas starting from the innermost lambda to
1087 // the outermost lambda, checking if '*this' is ever captured by copy - since
1088 // that could change the cv-qualifiers of the '*this' object.
1089 // The object referred to by '*this' starts out with the cv-qualifiers of its
1090 // member function. We then start with the innermost lambda and iterate
1091 // outward checking to see if any lambda performs a by-copy capture of '*this'
1092 // - and if so, any nested lambda must respect the 'constness' of that
1093 // capturing lamdbda's call operator.
1094 //
1095
1096 // Since the FunctionScopeInfo stack is representative of the lexical
1097 // nesting of the lambda expressions during initial parsing (and is the best
1098 // place for querying information about captures about lambdas that are
1099 // partially processed) and perhaps during instantiation of function templates
1100 // that contain lambda expressions that need to be transformed BUT not
1101 // necessarily during instantiation of a nested generic lambda's function call
1102 // operator (which might even be instantiated at the end of the TU) - at which
1103 // time the DeclContext tree is mature enough to query capture information
1104 // reliably - we use a two pronged approach to walk through all the lexically
1105 // enclosing lambda expressions:
1106 //
1107 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1108 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1109 // enclosed by the call-operator of the LSI below it on the stack (while
1110 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1111 // the stack represents the innermost lambda.
1112 //
1113 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1114 // represents a lambda's call operator. If it does, we must be instantiating
1115 // a generic lambda's call operator (represented by the Current LSI, and
1116 // should be the only scenario where an inconsistency between the LSI and the
1117 // DeclContext should occur), so climb out the DeclContexts if they
1118 // represent lambdas, while querying the corresponding closure types
1119 // regarding capture information.
1120
1121 // 1) Climb down the function scope info stack.
1122 for (int I = FunctionScopes.size();
1123 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1124 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1125 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1126 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1127 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1128
1129 if (!CurLSI->isCXXThisCaptured())
1130 continue;
1131
1132 auto C = CurLSI->getCXXThisCapture();
1133
1134 if (C.isCopyCapture()) {
1135 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1136 if (CurLSI->CallOperator->isConst())
1137 ClassType.addConst();
1138 return ASTCtx.getPointerType(ClassType);
1139 }
1140 }
1141
1142 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1143 // can happen during instantiation of its nested generic lambda call
1144 // operator); 2. if we're in a lambda scope (lambda body).
1145 if (CurLSI && isLambdaCallOperator(CurDC)) {
1146 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1147 "While computing 'this' capture-type for a generic lambda, when we "
1148 "run out of enclosing LSI's, yet the enclosing DC is a "
1149 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1150 "lambda call oeprator");
1151 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1152
1153 auto IsThisCaptured =
1154 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1155 IsConst = false;
1156 IsByCopy = false;
1157 for (auto &&C : Closure->captures()) {
1158 if (C.capturesThis()) {
1159 if (C.getCaptureKind() == LCK_StarThis)
1160 IsByCopy = true;
1161 if (Closure->getLambdaCallOperator()->isConst())
1162 IsConst = true;
1163 return true;
1164 }
1165 }
1166 return false;
1167 };
1168
1169 bool IsByCopyCapture = false;
1170 bool IsConstCapture = false;
1171 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1172 while (Closure &&
1173 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1174 if (IsByCopyCapture) {
1175 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1176 if (IsConstCapture)
1177 ClassType.addConst();
1178 return ASTCtx.getPointerType(ClassType);
1179 }
1180 Closure = isLambdaCallOperator(Closure->getParent())
1181 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1182 : nullptr;
1183 }
1184 }
1185 return ASTCtx.getPointerType(ClassType);
1186 }
1187
getCurrentThisType()1188 QualType Sema::getCurrentThisType() {
1189 DeclContext *DC = getFunctionLevelDeclContext();
1190 QualType ThisTy = CXXThisTypeOverride;
1191
1192 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1193 if (method && method->isInstance())
1194 ThisTy = method->getThisType();
1195 }
1196
1197 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1198 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1199
1200 // This is a lambda call operator that is being instantiated as a default
1201 // initializer. DC must point to the enclosing class type, so we can recover
1202 // the 'this' type from it.
1203 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1204 // There are no cv-qualifiers for 'this' within default initializers,
1205 // per [expr.prim.general]p4.
1206 ThisTy = Context.getPointerType(ClassTy);
1207 }
1208
1209 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1210 // might need to be adjusted if the lambda or any of its enclosing lambda's
1211 // captures '*this' by copy.
1212 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1213 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1214 CurContext, Context);
1215 return ThisTy;
1216 }
1217
CXXThisScopeRAII(Sema & S,Decl * ContextDecl,Qualifiers CXXThisTypeQuals,bool Enabled)1218 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1219 Decl *ContextDecl,
1220 Qualifiers CXXThisTypeQuals,
1221 bool Enabled)
1222 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1223 {
1224 if (!Enabled || !ContextDecl)
1225 return;
1226
1227 CXXRecordDecl *Record = nullptr;
1228 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1229 Record = Template->getTemplatedDecl();
1230 else
1231 Record = cast<CXXRecordDecl>(ContextDecl);
1232
1233 QualType T = S.Context.getRecordType(Record);
1234 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1235
1236 S.CXXThisTypeOverride = S.Context.getPointerType(T);
1237
1238 this->Enabled = true;
1239 }
1240
1241
~CXXThisScopeRAII()1242 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1243 if (Enabled) {
1244 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1245 }
1246 }
1247
buildLambdaThisCaptureFixit(Sema & Sema,LambdaScopeInfo * LSI)1248 static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) {
1249 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1250 assert(!LSI->isCXXThisCaptured());
1251 // [=, this] {}; // until C++20: Error: this when = is the default
1252 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval &&
1253 !Sema.getLangOpts().CPlusPlus20)
1254 return;
1255 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1256 << FixItHint::CreateInsertion(
1257 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1258 }
1259
CheckCXXThisCapture(SourceLocation Loc,const bool Explicit,bool BuildAndDiagnose,const unsigned * const FunctionScopeIndexToStopAt,const bool ByCopy)1260 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1261 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1262 const bool ByCopy) {
1263 // We don't need to capture this in an unevaluated context.
1264 if (isUnevaluatedContext() && !Explicit)
1265 return true;
1266
1267 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1268
1269 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1270 ? *FunctionScopeIndexToStopAt
1271 : FunctionScopes.size() - 1;
1272
1273 // Check that we can capture the *enclosing object* (referred to by '*this')
1274 // by the capturing-entity/closure (lambda/block/etc) at
1275 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1276
1277 // Note: The *enclosing object* can only be captured by-value by a
1278 // closure that is a lambda, using the explicit notation:
1279 // [*this] { ... }.
1280 // Every other capture of the *enclosing object* results in its by-reference
1281 // capture.
1282
1283 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1284 // stack), we can capture the *enclosing object* only if:
1285 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1286 // - or, 'L' has an implicit capture.
1287 // AND
1288 // -- there is no enclosing closure
1289 // -- or, there is some enclosing closure 'E' that has already captured the
1290 // *enclosing object*, and every intervening closure (if any) between 'E'
1291 // and 'L' can implicitly capture the *enclosing object*.
1292 // -- or, every enclosing closure can implicitly capture the
1293 // *enclosing object*
1294
1295
1296 unsigned NumCapturingClosures = 0;
1297 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1298 if (CapturingScopeInfo *CSI =
1299 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1300 if (CSI->CXXThisCaptureIndex != 0) {
1301 // 'this' is already being captured; there isn't anything more to do.
1302 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1303 break;
1304 }
1305 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1306 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1307 // This context can't implicitly capture 'this'; fail out.
1308 if (BuildAndDiagnose) {
1309 Diag(Loc, diag::err_this_capture)
1310 << (Explicit && idx == MaxFunctionScopesIndex);
1311 if (!Explicit)
1312 buildLambdaThisCaptureFixit(*this, LSI);
1313 }
1314 return true;
1315 }
1316 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1317 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1318 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1319 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1320 (Explicit && idx == MaxFunctionScopesIndex)) {
1321 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1322 // iteration through can be an explicit capture, all enclosing closures,
1323 // if any, must perform implicit captures.
1324
1325 // This closure can capture 'this'; continue looking upwards.
1326 NumCapturingClosures++;
1327 continue;
1328 }
1329 // This context can't implicitly capture 'this'; fail out.
1330 if (BuildAndDiagnose)
1331 Diag(Loc, diag::err_this_capture)
1332 << (Explicit && idx == MaxFunctionScopesIndex);
1333
1334 if (!Explicit)
1335 buildLambdaThisCaptureFixit(*this, LSI);
1336 return true;
1337 }
1338 break;
1339 }
1340 if (!BuildAndDiagnose) return false;
1341
1342 // If we got here, then the closure at MaxFunctionScopesIndex on the
1343 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1344 // (including implicit by-reference captures in any enclosing closures).
1345
1346 // In the loop below, respect the ByCopy flag only for the closure requesting
1347 // the capture (i.e. first iteration through the loop below). Ignore it for
1348 // all enclosing closure's up to NumCapturingClosures (since they must be
1349 // implicitly capturing the *enclosing object* by reference (see loop
1350 // above)).
1351 assert((!ByCopy ||
1352 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1353 "Only a lambda can capture the enclosing object (referred to by "
1354 "*this) by copy");
1355 QualType ThisTy = getCurrentThisType();
1356 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1357 --idx, --NumCapturingClosures) {
1358 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1359
1360 // The type of the corresponding data member (not a 'this' pointer if 'by
1361 // copy').
1362 QualType CaptureType = ThisTy;
1363 if (ByCopy) {
1364 // If we are capturing the object referred to by '*this' by copy, ignore
1365 // any cv qualifiers inherited from the type of the member function for
1366 // the type of the closure-type's corresponding data member and any use
1367 // of 'this'.
1368 CaptureType = ThisTy->getPointeeType();
1369 CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1370 }
1371
1372 bool isNested = NumCapturingClosures > 1;
1373 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1374 }
1375 return false;
1376 }
1377
ActOnCXXThis(SourceLocation Loc)1378 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1379 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1380 /// is a non-lvalue expression whose value is the address of the object for
1381 /// which the function is called.
1382
1383 QualType ThisTy = getCurrentThisType();
1384 if (ThisTy.isNull())
1385 return Diag(Loc, diag::err_invalid_this_use);
1386 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1387 }
1388
BuildCXXThisExpr(SourceLocation Loc,QualType Type,bool IsImplicit)1389 Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1390 bool IsImplicit) {
1391 auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1392 MarkThisReferenced(This);
1393 return This;
1394 }
1395
MarkThisReferenced(CXXThisExpr * This)1396 void Sema::MarkThisReferenced(CXXThisExpr *This) {
1397 CheckCXXThisCapture(This->getExprLoc());
1398 }
1399
isThisOutsideMemberFunctionBody(QualType BaseType)1400 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1401 // If we're outside the body of a member function, then we'll have a specified
1402 // type for 'this'.
1403 if (CXXThisTypeOverride.isNull())
1404 return false;
1405
1406 // Determine whether we're looking into a class that's currently being
1407 // defined.
1408 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1409 return Class && Class->isBeingDefined();
1410 }
1411
1412 /// Parse construction of a specified type.
1413 /// Can be interpreted either as function-style casting ("int(x)")
1414 /// or class type construction ("ClassType(x,y,z)")
1415 /// or creation of a value-initialized type ("int()").
1416 ExprResult
ActOnCXXTypeConstructExpr(ParsedType TypeRep,SourceLocation LParenOrBraceLoc,MultiExprArg exprs,SourceLocation RParenOrBraceLoc,bool ListInitialization)1417 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1418 SourceLocation LParenOrBraceLoc,
1419 MultiExprArg exprs,
1420 SourceLocation RParenOrBraceLoc,
1421 bool ListInitialization) {
1422 if (!TypeRep)
1423 return ExprError();
1424
1425 TypeSourceInfo *TInfo;
1426 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1427 if (!TInfo)
1428 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1429
1430 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1431 RParenOrBraceLoc, ListInitialization);
1432 // Avoid creating a non-type-dependent expression that contains typos.
1433 // Non-type-dependent expressions are liable to be discarded without
1434 // checking for embedded typos.
1435 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1436 !Result.get()->isTypeDependent())
1437 Result = CorrectDelayedTyposInExpr(Result.get());
1438 else if (Result.isInvalid())
1439 Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(),
1440 RParenOrBraceLoc, exprs, Ty);
1441 return Result;
1442 }
1443
1444 ExprResult
BuildCXXTypeConstructExpr(TypeSourceInfo * TInfo,SourceLocation LParenOrBraceLoc,MultiExprArg Exprs,SourceLocation RParenOrBraceLoc,bool ListInitialization)1445 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1446 SourceLocation LParenOrBraceLoc,
1447 MultiExprArg Exprs,
1448 SourceLocation RParenOrBraceLoc,
1449 bool ListInitialization) {
1450 QualType Ty = TInfo->getType();
1451 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1452
1453 assert((!ListInitialization ||
1454 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1455 "List initialization must have initializer list as expression.");
1456 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1457
1458 InitializedEntity Entity =
1459 InitializedEntity::InitializeTemporary(Context, TInfo);
1460 InitializationKind Kind =
1461 Exprs.size()
1462 ? ListInitialization
1463 ? InitializationKind::CreateDirectList(
1464 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1465 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1466 RParenOrBraceLoc)
1467 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1468 RParenOrBraceLoc);
1469
1470 // C++1z [expr.type.conv]p1:
1471 // If the type is a placeholder for a deduced class type, [...perform class
1472 // template argument deduction...]
1473 // C++2b:
1474 // Otherwise, if the type contains a placeholder type, it is replaced by the
1475 // type determined by placeholder type deduction.
1476 DeducedType *Deduced = Ty->getContainedDeducedType();
1477 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1478 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1479 Kind, Exprs);
1480 if (Ty.isNull())
1481 return ExprError();
1482 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1483 } else if (Deduced) {
1484 MultiExprArg Inits = Exprs;
1485 if (ListInitialization) {
1486 auto *ILE = cast<InitListExpr>(Exprs[0]);
1487 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1488 }
1489
1490 if (Inits.empty())
1491 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1492 << Ty << FullRange);
1493 if (Inits.size() > 1) {
1494 Expr *FirstBad = Inits[1];
1495 return ExprError(Diag(FirstBad->getBeginLoc(),
1496 diag::err_auto_expr_init_multiple_expressions)
1497 << Ty << FullRange);
1498 }
1499 if (getLangOpts().CPlusPlus2b) {
1500 if (Ty->getAs<AutoType>())
1501 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1502 }
1503 Expr *Deduce = Inits[0];
1504 if (isa<InitListExpr>(Deduce))
1505 return ExprError(
1506 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1507 << ListInitialization << Ty << FullRange);
1508 QualType DeducedType;
1509 if (DeduceAutoType(TInfo, Deduce, DeducedType) == DAR_Failed)
1510 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1511 << Ty << Deduce->getType() << FullRange
1512 << Deduce->getSourceRange());
1513 if (DeducedType.isNull())
1514 return ExprError();
1515
1516 Ty = DeducedType;
1517 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1518 }
1519
1520 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1521 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1522 // directly. We work around this by dropping the locations of the braces.
1523 SourceRange Locs = ListInitialization
1524 ? SourceRange()
1525 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1526 return CXXUnresolvedConstructExpr::Create(Context, Ty.getNonReferenceType(),
1527 TInfo, Locs.getBegin(), Exprs,
1528 Locs.getEnd());
1529 }
1530
1531 // C++ [expr.type.conv]p1:
1532 // If the expression list is a parenthesized single expression, the type
1533 // conversion expression is equivalent (in definedness, and if defined in
1534 // meaning) to the corresponding cast expression.
1535 if (Exprs.size() == 1 && !ListInitialization &&
1536 !isa<InitListExpr>(Exprs[0])) {
1537 Expr *Arg = Exprs[0];
1538 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1539 RParenOrBraceLoc);
1540 }
1541
1542 // For an expression of the form T(), T shall not be an array type.
1543 QualType ElemTy = Ty;
1544 if (Ty->isArrayType()) {
1545 if (!ListInitialization)
1546 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1547 << FullRange);
1548 ElemTy = Context.getBaseElementType(Ty);
1549 }
1550
1551 // Only construct objects with object types.
1552 // The standard doesn't explicitly forbid function types here, but that's an
1553 // obvious oversight, as there's no way to dynamically construct a function
1554 // in general.
1555 if (Ty->isFunctionType())
1556 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1557 << Ty << FullRange);
1558
1559 // C++17 [expr.type.conv]p2:
1560 // If the type is cv void and the initializer is (), the expression is a
1561 // prvalue of the specified type that performs no initialization.
1562 if (!Ty->isVoidType() &&
1563 RequireCompleteType(TyBeginLoc, ElemTy,
1564 diag::err_invalid_incomplete_type_use, FullRange))
1565 return ExprError();
1566
1567 // Otherwise, the expression is a prvalue of the specified type whose
1568 // result object is direct-initialized (11.6) with the initializer.
1569 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1570 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1571
1572 if (Result.isInvalid())
1573 return Result;
1574
1575 Expr *Inner = Result.get();
1576 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1577 Inner = BTE->getSubExpr();
1578 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1579 !isa<CXXScalarValueInitExpr>(Inner)) {
1580 // If we created a CXXTemporaryObjectExpr, that node also represents the
1581 // functional cast. Otherwise, create an explicit cast to represent
1582 // the syntactic form of a functional-style cast that was used here.
1583 //
1584 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1585 // would give a more consistent AST representation than using a
1586 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1587 // is sometimes handled by initialization and sometimes not.
1588 QualType ResultType = Result.get()->getType();
1589 SourceRange Locs = ListInitialization
1590 ? SourceRange()
1591 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1592 Result = CXXFunctionalCastExpr::Create(
1593 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1594 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1595 Locs.getBegin(), Locs.getEnd());
1596 }
1597
1598 return Result;
1599 }
1600
isUsualDeallocationFunction(const CXXMethodDecl * Method)1601 bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1602 // [CUDA] Ignore this function, if we can't call it.
1603 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1604 if (getLangOpts().CUDA) {
1605 auto CallPreference = IdentifyCUDAPreference(Caller, Method);
1606 // If it's not callable at all, it's not the right function.
1607 if (CallPreference < CFP_WrongSide)
1608 return false;
1609 if (CallPreference == CFP_WrongSide) {
1610 // Maybe. We have to check if there are better alternatives.
1611 DeclContext::lookup_result R =
1612 Method->getDeclContext()->lookup(Method->getDeclName());
1613 for (const auto *D : R) {
1614 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1615 if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide)
1616 return false;
1617 }
1618 }
1619 // We've found no better variants.
1620 }
1621 }
1622
1623 SmallVector<const FunctionDecl*, 4> PreventedBy;
1624 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1625
1626 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1627 return Result;
1628
1629 // In case of CUDA, return true if none of the 1-argument deallocator
1630 // functions are actually callable.
1631 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1632 assert(FD->getNumParams() == 1 &&
1633 "Only single-operand functions should be in PreventedBy");
1634 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1635 });
1636 }
1637
1638 /// Determine whether the given function is a non-placement
1639 /// deallocation function.
isNonPlacementDeallocationFunction(Sema & S,FunctionDecl * FD)1640 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1641 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1642 return S.isUsualDeallocationFunction(Method);
1643
1644 if (FD->getOverloadedOperator() != OO_Delete &&
1645 FD->getOverloadedOperator() != OO_Array_Delete)
1646 return false;
1647
1648 unsigned UsualParams = 1;
1649
1650 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1651 S.Context.hasSameUnqualifiedType(
1652 FD->getParamDecl(UsualParams)->getType(),
1653 S.Context.getSizeType()))
1654 ++UsualParams;
1655
1656 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1657 S.Context.hasSameUnqualifiedType(
1658 FD->getParamDecl(UsualParams)->getType(),
1659 S.Context.getTypeDeclType(S.getStdAlignValT())))
1660 ++UsualParams;
1661
1662 return UsualParams == FD->getNumParams();
1663 }
1664
1665 namespace {
1666 struct UsualDeallocFnInfo {
UsualDeallocFnInfo__anon07929ab70a11::UsualDeallocFnInfo1667 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
UsualDeallocFnInfo__anon07929ab70a11::UsualDeallocFnInfo1668 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1669 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1670 Destroying(false), HasSizeT(false), HasAlignValT(false),
1671 CUDAPref(Sema::CFP_Native) {
1672 // A function template declaration is never a usual deallocation function.
1673 if (!FD)
1674 return;
1675 unsigned NumBaseParams = 1;
1676 if (FD->isDestroyingOperatorDelete()) {
1677 Destroying = true;
1678 ++NumBaseParams;
1679 }
1680
1681 if (NumBaseParams < FD->getNumParams() &&
1682 S.Context.hasSameUnqualifiedType(
1683 FD->getParamDecl(NumBaseParams)->getType(),
1684 S.Context.getSizeType())) {
1685 ++NumBaseParams;
1686 HasSizeT = true;
1687 }
1688
1689 if (NumBaseParams < FD->getNumParams() &&
1690 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1691 ++NumBaseParams;
1692 HasAlignValT = true;
1693 }
1694
1695 // In CUDA, determine how much we'd like / dislike to call this.
1696 if (S.getLangOpts().CUDA)
1697 if (auto *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
1698 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1699 }
1700
operator bool__anon07929ab70a11::UsualDeallocFnInfo1701 explicit operator bool() const { return FD; }
1702
isBetterThan__anon07929ab70a11::UsualDeallocFnInfo1703 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1704 bool WantAlign) const {
1705 // C++ P0722:
1706 // A destroying operator delete is preferred over a non-destroying
1707 // operator delete.
1708 if (Destroying != Other.Destroying)
1709 return Destroying;
1710
1711 // C++17 [expr.delete]p10:
1712 // If the type has new-extended alignment, a function with a parameter
1713 // of type std::align_val_t is preferred; otherwise a function without
1714 // such a parameter is preferred
1715 if (HasAlignValT != Other.HasAlignValT)
1716 return HasAlignValT == WantAlign;
1717
1718 if (HasSizeT != Other.HasSizeT)
1719 return HasSizeT == WantSize;
1720
1721 // Use CUDA call preference as a tiebreaker.
1722 return CUDAPref > Other.CUDAPref;
1723 }
1724
1725 DeclAccessPair Found;
1726 FunctionDecl *FD;
1727 bool Destroying, HasSizeT, HasAlignValT;
1728 Sema::CUDAFunctionPreference CUDAPref;
1729 };
1730 }
1731
1732 /// Determine whether a type has new-extended alignment. This may be called when
1733 /// the type is incomplete (for a delete-expression with an incomplete pointee
1734 /// type), in which case it will conservatively return false if the alignment is
1735 /// not known.
hasNewExtendedAlignment(Sema & S,QualType AllocType)1736 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1737 return S.getLangOpts().AlignedAllocation &&
1738 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1739 S.getASTContext().getTargetInfo().getNewAlign();
1740 }
1741
1742 /// Select the correct "usual" deallocation function to use from a selection of
1743 /// deallocation functions (either global or class-scope).
resolveDeallocationOverload(Sema & S,LookupResult & R,bool WantSize,bool WantAlign,llvm::SmallVectorImpl<UsualDeallocFnInfo> * BestFns=nullptr)1744 static UsualDeallocFnInfo resolveDeallocationOverload(
1745 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1746 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1747 UsualDeallocFnInfo Best;
1748
1749 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1750 UsualDeallocFnInfo Info(S, I.getPair());
1751 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1752 Info.CUDAPref == Sema::CFP_Never)
1753 continue;
1754
1755 if (!Best) {
1756 Best = Info;
1757 if (BestFns)
1758 BestFns->push_back(Info);
1759 continue;
1760 }
1761
1762 if (Best.isBetterThan(Info, WantSize, WantAlign))
1763 continue;
1764
1765 // If more than one preferred function is found, all non-preferred
1766 // functions are eliminated from further consideration.
1767 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1768 BestFns->clear();
1769
1770 Best = Info;
1771 if (BestFns)
1772 BestFns->push_back(Info);
1773 }
1774
1775 return Best;
1776 }
1777
1778 /// Determine whether a given type is a class for which 'delete[]' would call
1779 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1780 /// we need to store the array size (even if the type is
1781 /// trivially-destructible).
doesUsualArrayDeleteWantSize(Sema & S,SourceLocation loc,QualType allocType)1782 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1783 QualType allocType) {
1784 const RecordType *record =
1785 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1786 if (!record) return false;
1787
1788 // Try to find an operator delete[] in class scope.
1789
1790 DeclarationName deleteName =
1791 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1792 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1793 S.LookupQualifiedName(ops, record->getDecl());
1794
1795 // We're just doing this for information.
1796 ops.suppressDiagnostics();
1797
1798 // Very likely: there's no operator delete[].
1799 if (ops.empty()) return false;
1800
1801 // If it's ambiguous, it should be illegal to call operator delete[]
1802 // on this thing, so it doesn't matter if we allocate extra space or not.
1803 if (ops.isAmbiguous()) return false;
1804
1805 // C++17 [expr.delete]p10:
1806 // If the deallocation functions have class scope, the one without a
1807 // parameter of type std::size_t is selected.
1808 auto Best = resolveDeallocationOverload(
1809 S, ops, /*WantSize*/false,
1810 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1811 return Best && Best.HasSizeT;
1812 }
1813
1814 /// Parsed a C++ 'new' expression (C++ 5.3.4).
1815 ///
1816 /// E.g.:
1817 /// @code new (memory) int[size][4] @endcode
1818 /// or
1819 /// @code ::new Foo(23, "hello") @endcode
1820 ///
1821 /// \param StartLoc The first location of the expression.
1822 /// \param UseGlobal True if 'new' was prefixed with '::'.
1823 /// \param PlacementLParen Opening paren of the placement arguments.
1824 /// \param PlacementArgs Placement new arguments.
1825 /// \param PlacementRParen Closing paren of the placement arguments.
1826 /// \param TypeIdParens If the type is in parens, the source range.
1827 /// \param D The type to be allocated, as well as array dimensions.
1828 /// \param Initializer The initializing expression or initializer-list, or null
1829 /// if there is none.
1830 ExprResult
ActOnCXXNew(SourceLocation StartLoc,bool UseGlobal,SourceLocation PlacementLParen,MultiExprArg PlacementArgs,SourceLocation PlacementRParen,SourceRange TypeIdParens,Declarator & D,Expr * Initializer)1831 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1832 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1833 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1834 Declarator &D, Expr *Initializer) {
1835 Optional<Expr *> ArraySize;
1836 // If the specified type is an array, unwrap it and save the expression.
1837 if (D.getNumTypeObjects() > 0 &&
1838 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1839 DeclaratorChunk &Chunk = D.getTypeObject(0);
1840 if (D.getDeclSpec().hasAutoTypeSpec())
1841 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1842 << D.getSourceRange());
1843 if (Chunk.Arr.hasStatic)
1844 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1845 << D.getSourceRange());
1846 if (!Chunk.Arr.NumElts && !Initializer)
1847 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1848 << D.getSourceRange());
1849
1850 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1851 D.DropFirstTypeObject();
1852 }
1853
1854 // Every dimension shall be of constant size.
1855 if (ArraySize) {
1856 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1857 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1858 break;
1859
1860 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1861 if (Expr *NumElts = (Expr *)Array.NumElts) {
1862 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1863 // FIXME: GCC permits constant folding here. We should either do so consistently
1864 // or not do so at all, rather than changing behavior in C++14 onwards.
1865 if (getLangOpts().CPlusPlus14) {
1866 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1867 // shall be a converted constant expression (5.19) of type std::size_t
1868 // and shall evaluate to a strictly positive value.
1869 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1870 Array.NumElts
1871 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1872 CCEK_ArrayBound)
1873 .get();
1874 } else {
1875 Array.NumElts =
1876 VerifyIntegerConstantExpression(
1877 NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1878 .get();
1879 }
1880 if (!Array.NumElts)
1881 return ExprError();
1882 }
1883 }
1884 }
1885 }
1886
1887 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1888 QualType AllocType = TInfo->getType();
1889 if (D.isInvalidType())
1890 return ExprError();
1891
1892 SourceRange DirectInitRange;
1893 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1894 DirectInitRange = List->getSourceRange();
1895
1896 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1897 PlacementLParen, PlacementArgs, PlacementRParen,
1898 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1899 Initializer);
1900 }
1901
isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,Expr * Init)1902 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1903 Expr *Init) {
1904 if (!Init)
1905 return true;
1906 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1907 return PLE->getNumExprs() == 0;
1908 if (isa<ImplicitValueInitExpr>(Init))
1909 return true;
1910 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1911 return !CCE->isListInitialization() &&
1912 CCE->getConstructor()->isDefaultConstructor();
1913 else if (Style == CXXNewExpr::ListInit) {
1914 assert(isa<InitListExpr>(Init) &&
1915 "Shouldn't create list CXXConstructExprs for arrays.");
1916 return true;
1917 }
1918 return false;
1919 }
1920
1921 bool
isUnavailableAlignedAllocationFunction(const FunctionDecl & FD) const1922 Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1923 if (!getLangOpts().AlignedAllocationUnavailable)
1924 return false;
1925 if (FD.isDefined())
1926 return false;
1927 Optional<unsigned> AlignmentParam;
1928 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
1929 AlignmentParam)
1930 return true;
1931 return false;
1932 }
1933
1934 // Emit a diagnostic if an aligned allocation/deallocation function that is not
1935 // implemented in the standard library is selected.
diagnoseUnavailableAlignedAllocation(const FunctionDecl & FD,SourceLocation Loc)1936 void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1937 SourceLocation Loc) {
1938 if (isUnavailableAlignedAllocationFunction(FD)) {
1939 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1940 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1941 getASTContext().getTargetInfo().getPlatformName());
1942 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
1943
1944 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1945 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1946 Diag(Loc, diag::err_aligned_allocation_unavailable)
1947 << IsDelete << FD.getType().getAsString() << OSName
1948 << OSVersion.getAsString() << OSVersion.empty();
1949 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1950 }
1951 }
1952
1953 ExprResult
BuildCXXNew(SourceRange Range,bool UseGlobal,SourceLocation PlacementLParen,MultiExprArg PlacementArgs,SourceLocation PlacementRParen,SourceRange TypeIdParens,QualType AllocType,TypeSourceInfo * AllocTypeInfo,Optional<Expr * > ArraySize,SourceRange DirectInitRange,Expr * Initializer)1954 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1955 SourceLocation PlacementLParen,
1956 MultiExprArg PlacementArgs,
1957 SourceLocation PlacementRParen,
1958 SourceRange TypeIdParens,
1959 QualType AllocType,
1960 TypeSourceInfo *AllocTypeInfo,
1961 Optional<Expr *> ArraySize,
1962 SourceRange DirectInitRange,
1963 Expr *Initializer) {
1964 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1965 SourceLocation StartLoc = Range.getBegin();
1966
1967 CXXNewExpr::InitializationStyle initStyle;
1968 if (DirectInitRange.isValid()) {
1969 assert(Initializer && "Have parens but no initializer.");
1970 initStyle = CXXNewExpr::CallInit;
1971 } else if (Initializer && isa<InitListExpr>(Initializer))
1972 initStyle = CXXNewExpr::ListInit;
1973 else {
1974 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1975 isa<CXXConstructExpr>(Initializer)) &&
1976 "Initializer expression that cannot have been implicitly created.");
1977 initStyle = CXXNewExpr::NoInit;
1978 }
1979
1980 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
1981 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1982 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1983 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
1984 }
1985
1986 // C++11 [expr.new]p15:
1987 // A new-expression that creates an object of type T initializes that
1988 // object as follows:
1989 InitializationKind Kind
1990 // - If the new-initializer is omitted, the object is default-
1991 // initialized (8.5); if no initialization is performed,
1992 // the object has indeterminate value
1993 = initStyle == CXXNewExpr::NoInit
1994 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1995 // - Otherwise, the new-initializer is interpreted according to
1996 // the
1997 // initialization rules of 8.5 for direct-initialization.
1998 : initStyle == CXXNewExpr::ListInit
1999 ? InitializationKind::CreateDirectList(
2000 TypeRange.getBegin(), Initializer->getBeginLoc(),
2001 Initializer->getEndLoc())
2002 : InitializationKind::CreateDirect(TypeRange.getBegin(),
2003 DirectInitRange.getBegin(),
2004 DirectInitRange.getEnd());
2005
2006 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2007 auto *Deduced = AllocType->getContainedDeducedType();
2008 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
2009 if (ArraySize)
2010 return ExprError(
2011 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2012 diag::err_deduced_class_template_compound_type)
2013 << /*array*/ 2
2014 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2015
2016 InitializedEntity Entity
2017 = InitializedEntity::InitializeNew(StartLoc, AllocType);
2018 AllocType = DeduceTemplateSpecializationFromInitializer(
2019 AllocTypeInfo, Entity, Kind, Exprs);
2020 if (AllocType.isNull())
2021 return ExprError();
2022 } else if (Deduced) {
2023 MultiExprArg Inits = Exprs;
2024 bool Braced = (initStyle == CXXNewExpr::ListInit);
2025 if (Braced) {
2026 auto *ILE = cast<InitListExpr>(Exprs[0]);
2027 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2028 }
2029
2030 if (initStyle == CXXNewExpr::NoInit || Inits.empty())
2031 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2032 << AllocType << TypeRange);
2033 if (Inits.size() > 1) {
2034 Expr *FirstBad = Inits[1];
2035 return ExprError(Diag(FirstBad->getBeginLoc(),
2036 diag::err_auto_new_ctor_multiple_expressions)
2037 << AllocType << TypeRange);
2038 }
2039 if (Braced && !getLangOpts().CPlusPlus17)
2040 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2041 << AllocType << TypeRange;
2042 Expr *Deduce = Inits[0];
2043 if (isa<InitListExpr>(Deduce))
2044 return ExprError(
2045 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2046 << Braced << AllocType << TypeRange);
2047 QualType DeducedType;
2048 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
2049 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2050 << AllocType << Deduce->getType()
2051 << TypeRange << Deduce->getSourceRange());
2052 if (DeducedType.isNull())
2053 return ExprError();
2054 AllocType = DeducedType;
2055 }
2056
2057 // Per C++0x [expr.new]p5, the type being constructed may be a
2058 // typedef of an array type.
2059 if (!ArraySize) {
2060 if (const ConstantArrayType *Array
2061 = Context.getAsConstantArrayType(AllocType)) {
2062 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2063 Context.getSizeType(),
2064 TypeRange.getEnd());
2065 AllocType = Array->getElementType();
2066 }
2067 }
2068
2069 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2070 return ExprError();
2071
2072 // In ARC, infer 'retaining' for the allocated
2073 if (getLangOpts().ObjCAutoRefCount &&
2074 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2075 AllocType->isObjCLifetimeType()) {
2076 AllocType = Context.getLifetimeQualifiedType(AllocType,
2077 AllocType->getObjCARCImplicitLifetime());
2078 }
2079
2080 QualType ResultType = Context.getPointerType(AllocType);
2081
2082 if (ArraySize && *ArraySize &&
2083 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2084 ExprResult result = CheckPlaceholderExpr(*ArraySize);
2085 if (result.isInvalid()) return ExprError();
2086 ArraySize = result.get();
2087 }
2088 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2089 // integral or enumeration type with a non-negative value."
2090 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2091 // enumeration type, or a class type for which a single non-explicit
2092 // conversion function to integral or unscoped enumeration type exists.
2093 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2094 // std::size_t.
2095 llvm::Optional<uint64_t> KnownArraySize;
2096 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2097 ExprResult ConvertedSize;
2098 if (getLangOpts().CPlusPlus14) {
2099 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2100
2101 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2102 AA_Converting);
2103
2104 if (!ConvertedSize.isInvalid() &&
2105 (*ArraySize)->getType()->getAs<RecordType>())
2106 // Diagnose the compatibility of this conversion.
2107 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2108 << (*ArraySize)->getType() << 0 << "'size_t'";
2109 } else {
2110 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2111 protected:
2112 Expr *ArraySize;
2113
2114 public:
2115 SizeConvertDiagnoser(Expr *ArraySize)
2116 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2117 ArraySize(ArraySize) {}
2118
2119 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2120 QualType T) override {
2121 return S.Diag(Loc, diag::err_array_size_not_integral)
2122 << S.getLangOpts().CPlusPlus11 << T;
2123 }
2124
2125 SemaDiagnosticBuilder diagnoseIncomplete(
2126 Sema &S, SourceLocation Loc, QualType T) override {
2127 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2128 << T << ArraySize->getSourceRange();
2129 }
2130
2131 SemaDiagnosticBuilder diagnoseExplicitConv(
2132 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2133 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2134 }
2135
2136 SemaDiagnosticBuilder noteExplicitConv(
2137 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2138 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2139 << ConvTy->isEnumeralType() << ConvTy;
2140 }
2141
2142 SemaDiagnosticBuilder diagnoseAmbiguous(
2143 Sema &S, SourceLocation Loc, QualType T) override {
2144 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2145 }
2146
2147 SemaDiagnosticBuilder noteAmbiguous(
2148 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2149 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2150 << ConvTy->isEnumeralType() << ConvTy;
2151 }
2152
2153 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2154 QualType T,
2155 QualType ConvTy) override {
2156 return S.Diag(Loc,
2157 S.getLangOpts().CPlusPlus11
2158 ? diag::warn_cxx98_compat_array_size_conversion
2159 : diag::ext_array_size_conversion)
2160 << T << ConvTy->isEnumeralType() << ConvTy;
2161 }
2162 } SizeDiagnoser(*ArraySize);
2163
2164 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2165 SizeDiagnoser);
2166 }
2167 if (ConvertedSize.isInvalid())
2168 return ExprError();
2169
2170 ArraySize = ConvertedSize.get();
2171 QualType SizeType = (*ArraySize)->getType();
2172
2173 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2174 return ExprError();
2175
2176 // C++98 [expr.new]p7:
2177 // The expression in a direct-new-declarator shall have integral type
2178 // with a non-negative value.
2179 //
2180 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2181 // per CWG1464. Otherwise, if it's not a constant, we must have an
2182 // unparenthesized array type.
2183
2184 // We've already performed any required implicit conversion to integer or
2185 // unscoped enumeration type.
2186 // FIXME: Per CWG1464, we are required to check the value prior to
2187 // converting to size_t. This will never find a negative array size in
2188 // C++14 onwards, because Value is always unsigned here!
2189 if (Optional<llvm::APSInt> Value =
2190 (*ArraySize)->getIntegerConstantExpr(Context)) {
2191 if (Value->isSigned() && Value->isNegative()) {
2192 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2193 diag::err_typecheck_negative_array_size)
2194 << (*ArraySize)->getSourceRange());
2195 }
2196
2197 if (!AllocType->isDependentType()) {
2198 unsigned ActiveSizeBits =
2199 ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value);
2200 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2201 return ExprError(
2202 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2203 << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2204 }
2205
2206 KnownArraySize = Value->getZExtValue();
2207 } else if (TypeIdParens.isValid()) {
2208 // Can't have dynamic array size when the type-id is in parentheses.
2209 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2210 << (*ArraySize)->getSourceRange()
2211 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2212 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2213
2214 TypeIdParens = SourceRange();
2215 }
2216
2217 // Note that we do *not* convert the argument in any way. It can
2218 // be signed, larger than size_t, whatever.
2219 }
2220
2221 FunctionDecl *OperatorNew = nullptr;
2222 FunctionDecl *OperatorDelete = nullptr;
2223 unsigned Alignment =
2224 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2225 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2226 bool PassAlignment = getLangOpts().AlignedAllocation &&
2227 Alignment > NewAlignment;
2228
2229 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
2230 if (!AllocType->isDependentType() &&
2231 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2232 FindAllocationFunctions(
2233 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2234 AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2235 OperatorNew, OperatorDelete))
2236 return ExprError();
2237
2238 // If this is an array allocation, compute whether the usual array
2239 // deallocation function for the type has a size_t parameter.
2240 bool UsualArrayDeleteWantsSize = false;
2241 if (ArraySize && !AllocType->isDependentType())
2242 UsualArrayDeleteWantsSize =
2243 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2244
2245 SmallVector<Expr *, 8> AllPlaceArgs;
2246 if (OperatorNew) {
2247 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2248 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2249 : VariadicDoesNotApply;
2250
2251 // We've already converted the placement args, just fill in any default
2252 // arguments. Skip the first parameter because we don't have a corresponding
2253 // argument. Skip the second parameter too if we're passing in the
2254 // alignment; we've already filled it in.
2255 unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2256 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2257 NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2258 CallType))
2259 return ExprError();
2260
2261 if (!AllPlaceArgs.empty())
2262 PlacementArgs = AllPlaceArgs;
2263
2264 // We would like to perform some checking on the given `operator new` call,
2265 // but the PlacementArgs does not contain the implicit arguments,
2266 // namely allocation size and maybe allocation alignment,
2267 // so we need to conjure them.
2268
2269 QualType SizeTy = Context.getSizeType();
2270 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2271
2272 llvm::APInt SingleEltSize(
2273 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2274
2275 // How many bytes do we want to allocate here?
2276 llvm::Optional<llvm::APInt> AllocationSize;
2277 if (!ArraySize && !AllocType->isDependentType()) {
2278 // For non-array operator new, we only want to allocate one element.
2279 AllocationSize = SingleEltSize;
2280 } else if (KnownArraySize && !AllocType->isDependentType()) {
2281 // For array operator new, only deal with static array size case.
2282 bool Overflow;
2283 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2284 .umul_ov(SingleEltSize, Overflow);
2285 (void)Overflow;
2286 assert(
2287 !Overflow &&
2288 "Expected that all the overflows would have been handled already.");
2289 }
2290
2291 IntegerLiteral AllocationSizeLiteral(
2292 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2293 SizeTy, SourceLocation());
2294 // Otherwise, if we failed to constant-fold the allocation size, we'll
2295 // just give up and pass-in something opaque, that isn't a null pointer.
2296 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2297 OK_Ordinary, /*SourceExpr=*/nullptr);
2298
2299 // Let's synthesize the alignment argument in case we will need it.
2300 // Since we *really* want to allocate these on stack, this is slightly ugly
2301 // because there might not be a `std::align_val_t` type.
2302 EnumDecl *StdAlignValT = getStdAlignValT();
2303 QualType AlignValT =
2304 StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy;
2305 IntegerLiteral AlignmentLiteral(
2306 Context,
2307 llvm::APInt(Context.getTypeSize(SizeTy),
2308 Alignment / Context.getCharWidth()),
2309 SizeTy, SourceLocation());
2310 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2311 CK_IntegralCast, &AlignmentLiteral,
2312 VK_PRValue, FPOptionsOverride());
2313
2314 // Adjust placement args by prepending conjured size and alignment exprs.
2315 llvm::SmallVector<Expr *, 8> CallArgs;
2316 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2317 CallArgs.emplace_back(AllocationSize
2318 ? static_cast<Expr *>(&AllocationSizeLiteral)
2319 : &OpaqueAllocationSize);
2320 if (PassAlignment)
2321 CallArgs.emplace_back(&DesiredAlignment);
2322 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2323
2324 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2325
2326 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2327 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2328
2329 // Warn if the type is over-aligned and is being allocated by (unaligned)
2330 // global operator new.
2331 if (PlacementArgs.empty() && !PassAlignment &&
2332 (OperatorNew->isImplicit() ||
2333 (OperatorNew->getBeginLoc().isValid() &&
2334 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2335 if (Alignment > NewAlignment)
2336 Diag(StartLoc, diag::warn_overaligned_type)
2337 << AllocType
2338 << unsigned(Alignment / Context.getCharWidth())
2339 << unsigned(NewAlignment / Context.getCharWidth());
2340 }
2341 }
2342
2343 // Array 'new' can't have any initializers except empty parentheses.
2344 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2345 // dialect distinction.
2346 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2347 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2348 Exprs.back()->getEndLoc());
2349 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2350 return ExprError();
2351 }
2352
2353 // If we can perform the initialization, and we've not already done so,
2354 // do it now.
2355 if (!AllocType->isDependentType() &&
2356 !Expr::hasAnyTypeDependentArguments(Exprs)) {
2357 // The type we initialize is the complete type, including the array bound.
2358 QualType InitType;
2359 if (KnownArraySize)
2360 InitType = Context.getConstantArrayType(
2361 AllocType,
2362 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2363 *KnownArraySize),
2364 *ArraySize, ArrayType::Normal, 0);
2365 else if (ArraySize)
2366 InitType =
2367 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2368 else
2369 InitType = AllocType;
2370
2371 InitializedEntity Entity
2372 = InitializedEntity::InitializeNew(StartLoc, InitType);
2373 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2374 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2375 if (FullInit.isInvalid())
2376 return ExprError();
2377
2378 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2379 // we don't want the initialized object to be destructed.
2380 // FIXME: We should not create these in the first place.
2381 if (CXXBindTemporaryExpr *Binder =
2382 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2383 FullInit = Binder->getSubExpr();
2384
2385 Initializer = FullInit.get();
2386
2387 // FIXME: If we have a KnownArraySize, check that the array bound of the
2388 // initializer is no greater than that constant value.
2389
2390 if (ArraySize && !*ArraySize) {
2391 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2392 if (CAT) {
2393 // FIXME: Track that the array size was inferred rather than explicitly
2394 // specified.
2395 ArraySize = IntegerLiteral::Create(
2396 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2397 } else {
2398 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2399 << Initializer->getSourceRange();
2400 }
2401 }
2402 }
2403
2404 // Mark the new and delete operators as referenced.
2405 if (OperatorNew) {
2406 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2407 return ExprError();
2408 MarkFunctionReferenced(StartLoc, OperatorNew);
2409 }
2410 if (OperatorDelete) {
2411 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2412 return ExprError();
2413 MarkFunctionReferenced(StartLoc, OperatorDelete);
2414 }
2415
2416 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2417 PassAlignment, UsualArrayDeleteWantsSize,
2418 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2419 Initializer, ResultType, AllocTypeInfo, Range,
2420 DirectInitRange);
2421 }
2422
2423 /// Checks that a type is suitable as the allocated type
2424 /// in a new-expression.
CheckAllocatedType(QualType AllocType,SourceLocation Loc,SourceRange R)2425 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2426 SourceRange R) {
2427 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2428 // abstract class type or array thereof.
2429 if (AllocType->isFunctionType())
2430 return Diag(Loc, diag::err_bad_new_type)
2431 << AllocType << 0 << R;
2432 else if (AllocType->isReferenceType())
2433 return Diag(Loc, diag::err_bad_new_type)
2434 << AllocType << 1 << R;
2435 else if (!AllocType->isDependentType() &&
2436 RequireCompleteSizedType(
2437 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2438 return true;
2439 else if (RequireNonAbstractType(Loc, AllocType,
2440 diag::err_allocation_of_abstract_type))
2441 return true;
2442 else if (AllocType->isVariablyModifiedType())
2443 return Diag(Loc, diag::err_variably_modified_new_type)
2444 << AllocType;
2445 else if (AllocType.getAddressSpace() != LangAS::Default &&
2446 !getLangOpts().OpenCLCPlusPlus)
2447 return Diag(Loc, diag::err_address_space_qualified_new)
2448 << AllocType.getUnqualifiedType()
2449 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2450 else if (getLangOpts().ObjCAutoRefCount) {
2451 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2452 QualType BaseAllocType = Context.getBaseElementType(AT);
2453 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2454 BaseAllocType->isObjCLifetimeType())
2455 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2456 << BaseAllocType;
2457 }
2458 }
2459
2460 return false;
2461 }
2462
resolveAllocationOverload(Sema & S,LookupResult & R,SourceRange Range,SmallVectorImpl<Expr * > & Args,bool & PassAlignment,FunctionDecl * & Operator,OverloadCandidateSet * AlignedCandidates,Expr * AlignArg,bool Diagnose)2463 static bool resolveAllocationOverload(
2464 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2465 bool &PassAlignment, FunctionDecl *&Operator,
2466 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2467 OverloadCandidateSet Candidates(R.getNameLoc(),
2468 OverloadCandidateSet::CSK_Normal);
2469 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2470 Alloc != AllocEnd; ++Alloc) {
2471 // Even member operator new/delete are implicitly treated as
2472 // static, so don't use AddMemberCandidate.
2473 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2474
2475 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2476 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2477 /*ExplicitTemplateArgs=*/nullptr, Args,
2478 Candidates,
2479 /*SuppressUserConversions=*/false);
2480 continue;
2481 }
2482
2483 FunctionDecl *Fn = cast<FunctionDecl>(D);
2484 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2485 /*SuppressUserConversions=*/false);
2486 }
2487
2488 // Do the resolution.
2489 OverloadCandidateSet::iterator Best;
2490 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2491 case OR_Success: {
2492 // Got one!
2493 FunctionDecl *FnDecl = Best->Function;
2494 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2495 Best->FoundDecl) == Sema::AR_inaccessible)
2496 return true;
2497
2498 Operator = FnDecl;
2499 return false;
2500 }
2501
2502 case OR_No_Viable_Function:
2503 // C++17 [expr.new]p13:
2504 // If no matching function is found and the allocated object type has
2505 // new-extended alignment, the alignment argument is removed from the
2506 // argument list, and overload resolution is performed again.
2507 if (PassAlignment) {
2508 PassAlignment = false;
2509 AlignArg = Args[1];
2510 Args.erase(Args.begin() + 1);
2511 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2512 Operator, &Candidates, AlignArg,
2513 Diagnose);
2514 }
2515
2516 // MSVC will fall back on trying to find a matching global operator new
2517 // if operator new[] cannot be found. Also, MSVC will leak by not
2518 // generating a call to operator delete or operator delete[], but we
2519 // will not replicate that bug.
2520 // FIXME: Find out how this interacts with the std::align_val_t fallback
2521 // once MSVC implements it.
2522 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2523 S.Context.getLangOpts().MSVCCompat) {
2524 R.clear();
2525 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2526 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2527 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2528 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2529 Operator, /*Candidates=*/nullptr,
2530 /*AlignArg=*/nullptr, Diagnose);
2531 }
2532
2533 if (Diagnose) {
2534 // If this is an allocation of the form 'new (p) X' for some object
2535 // pointer p (or an expression that will decay to such a pointer),
2536 // diagnose the missing inclusion of <new>.
2537 if (!R.isClassLookup() && Args.size() == 2 &&
2538 (Args[1]->getType()->isObjectPointerType() ||
2539 Args[1]->getType()->isArrayType())) {
2540 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2541 << R.getLookupName() << Range;
2542 // Listing the candidates is unlikely to be useful; skip it.
2543 return true;
2544 }
2545
2546 // Finish checking all candidates before we note any. This checking can
2547 // produce additional diagnostics so can't be interleaved with our
2548 // emission of notes.
2549 //
2550 // For an aligned allocation, separately check the aligned and unaligned
2551 // candidates with their respective argument lists.
2552 SmallVector<OverloadCandidate*, 32> Cands;
2553 SmallVector<OverloadCandidate*, 32> AlignedCands;
2554 llvm::SmallVector<Expr*, 4> AlignedArgs;
2555 if (AlignedCandidates) {
2556 auto IsAligned = [](OverloadCandidate &C) {
2557 return C.Function->getNumParams() > 1 &&
2558 C.Function->getParamDecl(1)->getType()->isAlignValT();
2559 };
2560 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2561
2562 AlignedArgs.reserve(Args.size() + 1);
2563 AlignedArgs.push_back(Args[0]);
2564 AlignedArgs.push_back(AlignArg);
2565 AlignedArgs.append(Args.begin() + 1, Args.end());
2566 AlignedCands = AlignedCandidates->CompleteCandidates(
2567 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2568
2569 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2570 R.getNameLoc(), IsUnaligned);
2571 } else {
2572 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2573 R.getNameLoc());
2574 }
2575
2576 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2577 << R.getLookupName() << Range;
2578 if (AlignedCandidates)
2579 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2580 R.getNameLoc());
2581 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2582 }
2583 return true;
2584
2585 case OR_Ambiguous:
2586 if (Diagnose) {
2587 Candidates.NoteCandidates(
2588 PartialDiagnosticAt(R.getNameLoc(),
2589 S.PDiag(diag::err_ovl_ambiguous_call)
2590 << R.getLookupName() << Range),
2591 S, OCD_AmbiguousCandidates, Args);
2592 }
2593 return true;
2594
2595 case OR_Deleted: {
2596 if (Diagnose) {
2597 Candidates.NoteCandidates(
2598 PartialDiagnosticAt(R.getNameLoc(),
2599 S.PDiag(diag::err_ovl_deleted_call)
2600 << R.getLookupName() << Range),
2601 S, OCD_AllCandidates, Args);
2602 }
2603 return true;
2604 }
2605 }
2606 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2607 }
2608
FindAllocationFunctions(SourceLocation StartLoc,SourceRange Range,AllocationFunctionScope NewScope,AllocationFunctionScope DeleteScope,QualType AllocType,bool IsArray,bool & PassAlignment,MultiExprArg PlaceArgs,FunctionDecl * & OperatorNew,FunctionDecl * & OperatorDelete,bool Diagnose)2609 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2610 AllocationFunctionScope NewScope,
2611 AllocationFunctionScope DeleteScope,
2612 QualType AllocType, bool IsArray,
2613 bool &PassAlignment, MultiExprArg PlaceArgs,
2614 FunctionDecl *&OperatorNew,
2615 FunctionDecl *&OperatorDelete,
2616 bool Diagnose) {
2617 // --- Choosing an allocation function ---
2618 // C++ 5.3.4p8 - 14 & 18
2619 // 1) If looking in AFS_Global scope for allocation functions, only look in
2620 // the global scope. Else, if AFS_Class, only look in the scope of the
2621 // allocated class. If AFS_Both, look in both.
2622 // 2) If an array size is given, look for operator new[], else look for
2623 // operator new.
2624 // 3) The first argument is always size_t. Append the arguments from the
2625 // placement form.
2626
2627 SmallVector<Expr*, 8> AllocArgs;
2628 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2629
2630 // We don't care about the actual value of these arguments.
2631 // FIXME: Should the Sema create the expression and embed it in the syntax
2632 // tree? Or should the consumer just recalculate the value?
2633 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2634 IntegerLiteral Size(
2635 Context, llvm::APInt::getZero(Context.getTargetInfo().getPointerWidth(0)),
2636 Context.getSizeType(), SourceLocation());
2637 AllocArgs.push_back(&Size);
2638
2639 QualType AlignValT = Context.VoidTy;
2640 if (PassAlignment) {
2641 DeclareGlobalNewDelete();
2642 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2643 }
2644 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2645 if (PassAlignment)
2646 AllocArgs.push_back(&Align);
2647
2648 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2649
2650 // C++ [expr.new]p8:
2651 // If the allocated type is a non-array type, the allocation
2652 // function's name is operator new and the deallocation function's
2653 // name is operator delete. If the allocated type is an array
2654 // type, the allocation function's name is operator new[] and the
2655 // deallocation function's name is operator delete[].
2656 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2657 IsArray ? OO_Array_New : OO_New);
2658
2659 QualType AllocElemType = Context.getBaseElementType(AllocType);
2660
2661 // Find the allocation function.
2662 {
2663 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2664
2665 // C++1z [expr.new]p9:
2666 // If the new-expression begins with a unary :: operator, the allocation
2667 // function's name is looked up in the global scope. Otherwise, if the
2668 // allocated type is a class type T or array thereof, the allocation
2669 // function's name is looked up in the scope of T.
2670 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2671 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2672
2673 // We can see ambiguity here if the allocation function is found in
2674 // multiple base classes.
2675 if (R.isAmbiguous())
2676 return true;
2677
2678 // If this lookup fails to find the name, or if the allocated type is not
2679 // a class type, the allocation function's name is looked up in the
2680 // global scope.
2681 if (R.empty()) {
2682 if (NewScope == AFS_Class)
2683 return true;
2684
2685 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2686 }
2687
2688 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2689 if (PlaceArgs.empty()) {
2690 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2691 } else {
2692 Diag(StartLoc, diag::err_openclcxx_placement_new);
2693 }
2694 return true;
2695 }
2696
2697 assert(!R.empty() && "implicitly declared allocation functions not found");
2698 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2699
2700 // We do our own custom access checks below.
2701 R.suppressDiagnostics();
2702
2703 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2704 OperatorNew, /*Candidates=*/nullptr,
2705 /*AlignArg=*/nullptr, Diagnose))
2706 return true;
2707 }
2708
2709 // We don't need an operator delete if we're running under -fno-exceptions.
2710 if (!getLangOpts().Exceptions) {
2711 OperatorDelete = nullptr;
2712 return false;
2713 }
2714
2715 // Note, the name of OperatorNew might have been changed from array to
2716 // non-array by resolveAllocationOverload.
2717 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2718 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2719 ? OO_Array_Delete
2720 : OO_Delete);
2721
2722 // C++ [expr.new]p19:
2723 //
2724 // If the new-expression begins with a unary :: operator, the
2725 // deallocation function's name is looked up in the global
2726 // scope. Otherwise, if the allocated type is a class type T or an
2727 // array thereof, the deallocation function's name is looked up in
2728 // the scope of T. If this lookup fails to find the name, or if
2729 // the allocated type is not a class type or array thereof, the
2730 // deallocation function's name is looked up in the global scope.
2731 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2732 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2733 auto *RD =
2734 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2735 LookupQualifiedName(FoundDelete, RD);
2736 }
2737 if (FoundDelete.isAmbiguous())
2738 return true; // FIXME: clean up expressions?
2739
2740 // Filter out any destroying operator deletes. We can't possibly call such a
2741 // function in this context, because we're handling the case where the object
2742 // was not successfully constructed.
2743 // FIXME: This is not covered by the language rules yet.
2744 {
2745 LookupResult::Filter Filter = FoundDelete.makeFilter();
2746 while (Filter.hasNext()) {
2747 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2748 if (FD && FD->isDestroyingOperatorDelete())
2749 Filter.erase();
2750 }
2751 Filter.done();
2752 }
2753
2754 bool FoundGlobalDelete = FoundDelete.empty();
2755 if (FoundDelete.empty()) {
2756 FoundDelete.clear(LookupOrdinaryName);
2757
2758 if (DeleteScope == AFS_Class)
2759 return true;
2760
2761 DeclareGlobalNewDelete();
2762 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2763 }
2764
2765 FoundDelete.suppressDiagnostics();
2766
2767 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2768
2769 // Whether we're looking for a placement operator delete is dictated
2770 // by whether we selected a placement operator new, not by whether
2771 // we had explicit placement arguments. This matters for things like
2772 // struct A { void *operator new(size_t, int = 0); ... };
2773 // A *a = new A()
2774 //
2775 // We don't have any definition for what a "placement allocation function"
2776 // is, but we assume it's any allocation function whose
2777 // parameter-declaration-clause is anything other than (size_t).
2778 //
2779 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2780 // This affects whether an exception from the constructor of an overaligned
2781 // type uses the sized or non-sized form of aligned operator delete.
2782 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2783 OperatorNew->isVariadic();
2784
2785 if (isPlacementNew) {
2786 // C++ [expr.new]p20:
2787 // A declaration of a placement deallocation function matches the
2788 // declaration of a placement allocation function if it has the
2789 // same number of parameters and, after parameter transformations
2790 // (8.3.5), all parameter types except the first are
2791 // identical. [...]
2792 //
2793 // To perform this comparison, we compute the function type that
2794 // the deallocation function should have, and use that type both
2795 // for template argument deduction and for comparison purposes.
2796 QualType ExpectedFunctionType;
2797 {
2798 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2799
2800 SmallVector<QualType, 4> ArgTypes;
2801 ArgTypes.push_back(Context.VoidPtrTy);
2802 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2803 ArgTypes.push_back(Proto->getParamType(I));
2804
2805 FunctionProtoType::ExtProtoInfo EPI;
2806 // FIXME: This is not part of the standard's rule.
2807 EPI.Variadic = Proto->isVariadic();
2808
2809 ExpectedFunctionType
2810 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2811 }
2812
2813 for (LookupResult::iterator D = FoundDelete.begin(),
2814 DEnd = FoundDelete.end();
2815 D != DEnd; ++D) {
2816 FunctionDecl *Fn = nullptr;
2817 if (FunctionTemplateDecl *FnTmpl =
2818 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2819 // Perform template argument deduction to try to match the
2820 // expected function type.
2821 TemplateDeductionInfo Info(StartLoc);
2822 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2823 Info))
2824 continue;
2825 } else
2826 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2827
2828 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2829 ExpectedFunctionType,
2830 /*AdjustExcpetionSpec*/true),
2831 ExpectedFunctionType))
2832 Matches.push_back(std::make_pair(D.getPair(), Fn));
2833 }
2834
2835 if (getLangOpts().CUDA)
2836 EraseUnwantedCUDAMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2837 Matches);
2838 } else {
2839 // C++1y [expr.new]p22:
2840 // For a non-placement allocation function, the normal deallocation
2841 // function lookup is used
2842 //
2843 // Per [expr.delete]p10, this lookup prefers a member operator delete
2844 // without a size_t argument, but prefers a non-member operator delete
2845 // with a size_t where possible (which it always is in this case).
2846 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2847 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2848 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2849 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2850 &BestDeallocFns);
2851 if (Selected)
2852 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2853 else {
2854 // If we failed to select an operator, all remaining functions are viable
2855 // but ambiguous.
2856 for (auto Fn : BestDeallocFns)
2857 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2858 }
2859 }
2860
2861 // C++ [expr.new]p20:
2862 // [...] If the lookup finds a single matching deallocation
2863 // function, that function will be called; otherwise, no
2864 // deallocation function will be called.
2865 if (Matches.size() == 1) {
2866 OperatorDelete = Matches[0].second;
2867
2868 // C++1z [expr.new]p23:
2869 // If the lookup finds a usual deallocation function (3.7.4.2)
2870 // with a parameter of type std::size_t and that function, considered
2871 // as a placement deallocation function, would have been
2872 // selected as a match for the allocation function, the program
2873 // is ill-formed.
2874 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2875 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2876 UsualDeallocFnInfo Info(*this,
2877 DeclAccessPair::make(OperatorDelete, AS_public));
2878 // Core issue, per mail to core reflector, 2016-10-09:
2879 // If this is a member operator delete, and there is a corresponding
2880 // non-sized member operator delete, this isn't /really/ a sized
2881 // deallocation function, it just happens to have a size_t parameter.
2882 bool IsSizedDelete = Info.HasSizeT;
2883 if (IsSizedDelete && !FoundGlobalDelete) {
2884 auto NonSizedDelete =
2885 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2886 /*WantAlign*/Info.HasAlignValT);
2887 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2888 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2889 IsSizedDelete = false;
2890 }
2891
2892 if (IsSizedDelete) {
2893 SourceRange R = PlaceArgs.empty()
2894 ? SourceRange()
2895 : SourceRange(PlaceArgs.front()->getBeginLoc(),
2896 PlaceArgs.back()->getEndLoc());
2897 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2898 if (!OperatorDelete->isImplicit())
2899 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2900 << DeleteName;
2901 }
2902 }
2903
2904 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2905 Matches[0].first);
2906 } else if (!Matches.empty()) {
2907 // We found multiple suitable operators. Per [expr.new]p20, that means we
2908 // call no 'operator delete' function, but we should at least warn the user.
2909 // FIXME: Suppress this warning if the construction cannot throw.
2910 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2911 << DeleteName << AllocElemType;
2912
2913 for (auto &Match : Matches)
2914 Diag(Match.second->getLocation(),
2915 diag::note_member_declared_here) << DeleteName;
2916 }
2917
2918 return false;
2919 }
2920
2921 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2922 /// delete. These are:
2923 /// @code
2924 /// // C++03:
2925 /// void* operator new(std::size_t) throw(std::bad_alloc);
2926 /// void* operator new[](std::size_t) throw(std::bad_alloc);
2927 /// void operator delete(void *) throw();
2928 /// void operator delete[](void *) throw();
2929 /// // C++11:
2930 /// void* operator new(std::size_t);
2931 /// void* operator new[](std::size_t);
2932 /// void operator delete(void *) noexcept;
2933 /// void operator delete[](void *) noexcept;
2934 /// // C++1y:
2935 /// void* operator new(std::size_t);
2936 /// void* operator new[](std::size_t);
2937 /// void operator delete(void *) noexcept;
2938 /// void operator delete[](void *) noexcept;
2939 /// void operator delete(void *, std::size_t) noexcept;
2940 /// void operator delete[](void *, std::size_t) noexcept;
2941 /// @endcode
2942 /// Note that the placement and nothrow forms of new are *not* implicitly
2943 /// declared. Their use requires including \<new\>.
DeclareGlobalNewDelete()2944 void Sema::DeclareGlobalNewDelete() {
2945 if (GlobalNewDeleteDeclared)
2946 return;
2947
2948 // The implicitly declared new and delete operators
2949 // are not supported in OpenCL.
2950 if (getLangOpts().OpenCLCPlusPlus)
2951 return;
2952
2953 // C++ [basic.std.dynamic]p2:
2954 // [...] The following allocation and deallocation functions (18.4) are
2955 // implicitly declared in global scope in each translation unit of a
2956 // program
2957 //
2958 // C++03:
2959 // void* operator new(std::size_t) throw(std::bad_alloc);
2960 // void* operator new[](std::size_t) throw(std::bad_alloc);
2961 // void operator delete(void*) throw();
2962 // void operator delete[](void*) throw();
2963 // C++11:
2964 // void* operator new(std::size_t);
2965 // void* operator new[](std::size_t);
2966 // void operator delete(void*) noexcept;
2967 // void operator delete[](void*) noexcept;
2968 // C++1y:
2969 // void* operator new(std::size_t);
2970 // void* operator new[](std::size_t);
2971 // void operator delete(void*) noexcept;
2972 // void operator delete[](void*) noexcept;
2973 // void operator delete(void*, std::size_t) noexcept;
2974 // void operator delete[](void*, std::size_t) noexcept;
2975 //
2976 // These implicit declarations introduce only the function names operator
2977 // new, operator new[], operator delete, operator delete[].
2978 //
2979 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2980 // "std" or "bad_alloc" as necessary to form the exception specification.
2981 // However, we do not make these implicit declarations visible to name
2982 // lookup.
2983 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2984 // The "std::bad_alloc" class has not yet been declared, so build it
2985 // implicitly.
2986 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2987 getOrCreateStdNamespace(),
2988 SourceLocation(), SourceLocation(),
2989 &PP.getIdentifierTable().get("bad_alloc"),
2990 nullptr);
2991 getStdBadAlloc()->setImplicit(true);
2992 }
2993 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2994 // The "std::align_val_t" enum class has not yet been declared, so build it
2995 // implicitly.
2996 auto *AlignValT = EnumDecl::Create(
2997 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2998 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2999 AlignValT->setIntegerType(Context.getSizeType());
3000 AlignValT->setPromotionType(Context.getSizeType());
3001 AlignValT->setImplicit(true);
3002 StdAlignValT = AlignValT;
3003 }
3004
3005 GlobalNewDeleteDeclared = true;
3006
3007 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
3008 QualType SizeT = Context.getSizeType();
3009
3010 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3011 QualType Return, QualType Param) {
3012 llvm::SmallVector<QualType, 3> Params;
3013 Params.push_back(Param);
3014
3015 // Create up to four variants of the function (sized/aligned).
3016 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3017 (Kind == OO_Delete || Kind == OO_Array_Delete);
3018 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3019
3020 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3021 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3022 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3023 if (Sized)
3024 Params.push_back(SizeT);
3025
3026 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3027 if (Aligned)
3028 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3029
3030 DeclareGlobalAllocationFunction(
3031 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3032
3033 if (Aligned)
3034 Params.pop_back();
3035 }
3036 }
3037 };
3038
3039 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3040 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3041 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3042 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3043 }
3044
3045 /// DeclareGlobalAllocationFunction - Declares a single implicit global
3046 /// allocation function if it doesn't already exist.
DeclareGlobalAllocationFunction(DeclarationName Name,QualType Return,ArrayRef<QualType> Params)3047 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
3048 QualType Return,
3049 ArrayRef<QualType> Params) {
3050 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
3051
3052 // Check if this function is already declared.
3053 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3054 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3055 Alloc != AllocEnd; ++Alloc) {
3056 // Only look at non-template functions, as it is the predefined,
3057 // non-templated allocation function we are trying to declare here.
3058 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3059 if (Func->getNumParams() == Params.size()) {
3060 llvm::SmallVector<QualType, 3> FuncParams;
3061 for (auto *P : Func->parameters())
3062 FuncParams.push_back(
3063 Context.getCanonicalType(P->getType().getUnqualifiedType()));
3064 if (llvm::makeArrayRef(FuncParams) == Params) {
3065 // Make the function visible to name lookup, even if we found it in
3066 // an unimported module. It either is an implicitly-declared global
3067 // allocation function, or is suppressing that function.
3068 Func->setVisibleDespiteOwningModule();
3069 return;
3070 }
3071 }
3072 }
3073 }
3074
3075 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
3076 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3077
3078 QualType BadAllocType;
3079 bool HasBadAllocExceptionSpec
3080 = (Name.getCXXOverloadedOperator() == OO_New ||
3081 Name.getCXXOverloadedOperator() == OO_Array_New);
3082 if (HasBadAllocExceptionSpec) {
3083 if (!getLangOpts().CPlusPlus11) {
3084 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3085 assert(StdBadAlloc && "Must have std::bad_alloc declared");
3086 EPI.ExceptionSpec.Type = EST_Dynamic;
3087 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
3088 }
3089 if (getLangOpts().NewInfallible) {
3090 EPI.ExceptionSpec.Type = EST_DynamicNone;
3091 }
3092 } else {
3093 EPI.ExceptionSpec =
3094 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
3095 }
3096
3097 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3098 QualType FnType = Context.getFunctionType(Return, Params, EPI);
3099 FunctionDecl *Alloc = FunctionDecl::Create(
3100 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3101 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3102 true);
3103 Alloc->setImplicit();
3104 // Global allocation functions should always be visible.
3105 Alloc->setVisibleDespiteOwningModule();
3106
3107 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible)
3108 Alloc->addAttr(
3109 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3110
3111 Alloc->addAttr(VisibilityAttr::CreateImplicit(
3112 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
3113 ? VisibilityAttr::Hidden
3114 : VisibilityAttr::Default));
3115
3116 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
3117 for (QualType T : Params) {
3118 ParamDecls.push_back(ParmVarDecl::Create(
3119 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3120 /*TInfo=*/nullptr, SC_None, nullptr));
3121 ParamDecls.back()->setImplicit();
3122 }
3123 Alloc->setParams(ParamDecls);
3124 if (ExtraAttr)
3125 Alloc->addAttr(ExtraAttr);
3126 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);
3127 Context.getTranslationUnitDecl()->addDecl(Alloc);
3128 IdResolver.tryAddTopLevelDecl(Alloc, Name);
3129 };
3130
3131 if (!LangOpts.CUDA)
3132 CreateAllocationFunctionDecl(nullptr);
3133 else {
3134 // Host and device get their own declaration so each can be
3135 // defined or re-declared independently.
3136 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3137 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3138 }
3139 }
3140
FindUsualDeallocationFunction(SourceLocation StartLoc,bool CanProvideSize,bool Overaligned,DeclarationName Name)3141 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
3142 bool CanProvideSize,
3143 bool Overaligned,
3144 DeclarationName Name) {
3145 DeclareGlobalNewDelete();
3146
3147 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3148 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
3149
3150 // FIXME: It's possible for this to result in ambiguity, through a
3151 // user-declared variadic operator delete or the enable_if attribute. We
3152 // should probably not consider those cases to be usual deallocation
3153 // functions. But for now we just make an arbitrary choice in that case.
3154 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3155 Overaligned);
3156 assert(Result.FD && "operator delete missing from global scope?");
3157 return Result.FD;
3158 }
3159
FindDeallocationFunctionForDestructor(SourceLocation Loc,CXXRecordDecl * RD)3160 FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
3161 CXXRecordDecl *RD) {
3162 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3163
3164 FunctionDecl *OperatorDelete = nullptr;
3165 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3166 return nullptr;
3167 if (OperatorDelete)
3168 return OperatorDelete;
3169
3170 // If there's no class-specific operator delete, look up the global
3171 // non-array delete.
3172 return FindUsualDeallocationFunction(
3173 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
3174 Name);
3175 }
3176
FindDeallocationFunction(SourceLocation StartLoc,CXXRecordDecl * RD,DeclarationName Name,FunctionDecl * & Operator,bool Diagnose)3177 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3178 DeclarationName Name,
3179 FunctionDecl *&Operator, bool Diagnose) {
3180 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3181 // Try to find operator delete/operator delete[] in class scope.
3182 LookupQualifiedName(Found, RD);
3183
3184 if (Found.isAmbiguous())
3185 return true;
3186
3187 Found.suppressDiagnostics();
3188
3189 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3190
3191 // C++17 [expr.delete]p10:
3192 // If the deallocation functions have class scope, the one without a
3193 // parameter of type std::size_t is selected.
3194 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
3195 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
3196 /*WantAlign*/ Overaligned, &Matches);
3197
3198 // If we could find an overload, use it.
3199 if (Matches.size() == 1) {
3200 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3201
3202 // FIXME: DiagnoseUseOfDecl?
3203 if (Operator->isDeleted()) {
3204 if (Diagnose) {
3205 Diag(StartLoc, diag::err_deleted_function_use);
3206 NoteDeletedFunction(Operator);
3207 }
3208 return true;
3209 }
3210
3211 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3212 Matches[0].Found, Diagnose) == AR_inaccessible)
3213 return true;
3214
3215 return false;
3216 }
3217
3218 // We found multiple suitable operators; complain about the ambiguity.
3219 // FIXME: The standard doesn't say to do this; it appears that the intent
3220 // is that this should never happen.
3221 if (!Matches.empty()) {
3222 if (Diagnose) {
3223 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3224 << Name << RD;
3225 for (auto &Match : Matches)
3226 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3227 }
3228 return true;
3229 }
3230
3231 // We did find operator delete/operator delete[] declarations, but
3232 // none of them were suitable.
3233 if (!Found.empty()) {
3234 if (Diagnose) {
3235 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3236 << Name << RD;
3237
3238 for (NamedDecl *D : Found)
3239 Diag(D->getUnderlyingDecl()->getLocation(),
3240 diag::note_member_declared_here) << Name;
3241 }
3242 return true;
3243 }
3244
3245 Operator = nullptr;
3246 return false;
3247 }
3248
3249 namespace {
3250 /// Checks whether delete-expression, and new-expression used for
3251 /// initializing deletee have the same array form.
3252 class MismatchingNewDeleteDetector {
3253 public:
3254 enum MismatchResult {
3255 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3256 NoMismatch,
3257 /// Indicates that variable is initialized with mismatching form of \a new.
3258 VarInitMismatches,
3259 /// Indicates that member is initialized with mismatching form of \a new.
3260 MemberInitMismatches,
3261 /// Indicates that 1 or more constructors' definitions could not been
3262 /// analyzed, and they will be checked again at the end of translation unit.
3263 AnalyzeLater
3264 };
3265
3266 /// \param EndOfTU True, if this is the final analysis at the end of
3267 /// translation unit. False, if this is the initial analysis at the point
3268 /// delete-expression was encountered.
MismatchingNewDeleteDetector(bool EndOfTU)3269 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3270 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3271 HasUndefinedConstructors(false) {}
3272
3273 /// Checks whether pointee of a delete-expression is initialized with
3274 /// matching form of new-expression.
3275 ///
3276 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3277 /// point where delete-expression is encountered, then a warning will be
3278 /// issued immediately. If return value is \c AnalyzeLater at the point where
3279 /// delete-expression is seen, then member will be analyzed at the end of
3280 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3281 /// couldn't be analyzed. If at least one constructor initializes the member
3282 /// with matching type of new, the return value is \c NoMismatch.
3283 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3284 /// Analyzes a class member.
3285 /// \param Field Class member to analyze.
3286 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3287 /// for deleting the \p Field.
3288 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3289 FieldDecl *Field;
3290 /// List of mismatching new-expressions used for initialization of the pointee
3291 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3292 /// Indicates whether delete-expression was in array form.
3293 bool IsArrayForm;
3294
3295 private:
3296 const bool EndOfTU;
3297 /// Indicates that there is at least one constructor without body.
3298 bool HasUndefinedConstructors;
3299 /// Returns \c CXXNewExpr from given initialization expression.
3300 /// \param E Expression used for initializing pointee in delete-expression.
3301 /// E can be a single-element \c InitListExpr consisting of new-expression.
3302 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3303 /// Returns whether member is initialized with mismatching form of
3304 /// \c new either by the member initializer or in-class initialization.
3305 ///
3306 /// If bodies of all constructors are not visible at the end of translation
3307 /// unit or at least one constructor initializes member with the matching
3308 /// form of \c new, mismatch cannot be proven, and this function will return
3309 /// \c NoMismatch.
3310 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3311 /// Returns whether variable is initialized with mismatching form of
3312 /// \c new.
3313 ///
3314 /// If variable is initialized with matching form of \c new or variable is not
3315 /// initialized with a \c new expression, this function will return true.
3316 /// If variable is initialized with mismatching form of \c new, returns false.
3317 /// \param D Variable to analyze.
3318 bool hasMatchingVarInit(const DeclRefExpr *D);
3319 /// Checks whether the constructor initializes pointee with mismatching
3320 /// form of \c new.
3321 ///
3322 /// Returns true, if member is initialized with matching form of \c new in
3323 /// member initializer list. Returns false, if member is initialized with the
3324 /// matching form of \c new in this constructor's initializer or given
3325 /// constructor isn't defined at the point where delete-expression is seen, or
3326 /// member isn't initialized by the constructor.
3327 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3328 /// Checks whether member is initialized with matching form of
3329 /// \c new in member initializer list.
3330 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3331 /// Checks whether member is initialized with mismatching form of \c new by
3332 /// in-class initializer.
3333 MismatchResult analyzeInClassInitializer();
3334 };
3335 }
3336
3337 MismatchingNewDeleteDetector::MismatchResult
analyzeDeleteExpr(const CXXDeleteExpr * DE)3338 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3339 NewExprs.clear();
3340 assert(DE && "Expected delete-expression");
3341 IsArrayForm = DE->isArrayForm();
3342 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3343 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3344 return analyzeMemberExpr(ME);
3345 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3346 if (!hasMatchingVarInit(D))
3347 return VarInitMismatches;
3348 }
3349 return NoMismatch;
3350 }
3351
3352 const CXXNewExpr *
getNewExprFromInitListOrExpr(const Expr * E)3353 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3354 assert(E != nullptr && "Expected a valid initializer expression");
3355 E = E->IgnoreParenImpCasts();
3356 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3357 if (ILE->getNumInits() == 1)
3358 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3359 }
3360
3361 return dyn_cast_or_null<const CXXNewExpr>(E);
3362 }
3363
hasMatchingNewInCtorInit(const CXXCtorInitializer * CI)3364 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3365 const CXXCtorInitializer *CI) {
3366 const CXXNewExpr *NE = nullptr;
3367 if (Field == CI->getMember() &&
3368 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3369 if (NE->isArray() == IsArrayForm)
3370 return true;
3371 else
3372 NewExprs.push_back(NE);
3373 }
3374 return false;
3375 }
3376
hasMatchingNewInCtor(const CXXConstructorDecl * CD)3377 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3378 const CXXConstructorDecl *CD) {
3379 if (CD->isImplicit())
3380 return false;
3381 const FunctionDecl *Definition = CD;
3382 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3383 HasUndefinedConstructors = true;
3384 return EndOfTU;
3385 }
3386 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3387 if (hasMatchingNewInCtorInit(CI))
3388 return true;
3389 }
3390 return false;
3391 }
3392
3393 MismatchingNewDeleteDetector::MismatchResult
analyzeInClassInitializer()3394 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3395 assert(Field != nullptr && "This should be called only for members");
3396 const Expr *InitExpr = Field->getInClassInitializer();
3397 if (!InitExpr)
3398 return EndOfTU ? NoMismatch : AnalyzeLater;
3399 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3400 if (NE->isArray() != IsArrayForm) {
3401 NewExprs.push_back(NE);
3402 return MemberInitMismatches;
3403 }
3404 }
3405 return NoMismatch;
3406 }
3407
3408 MismatchingNewDeleteDetector::MismatchResult
analyzeField(FieldDecl * Field,bool DeleteWasArrayForm)3409 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3410 bool DeleteWasArrayForm) {
3411 assert(Field != nullptr && "Analysis requires a valid class member.");
3412 this->Field = Field;
3413 IsArrayForm = DeleteWasArrayForm;
3414 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3415 for (const auto *CD : RD->ctors()) {
3416 if (hasMatchingNewInCtor(CD))
3417 return NoMismatch;
3418 }
3419 if (HasUndefinedConstructors)
3420 return EndOfTU ? NoMismatch : AnalyzeLater;
3421 if (!NewExprs.empty())
3422 return MemberInitMismatches;
3423 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3424 : NoMismatch;
3425 }
3426
3427 MismatchingNewDeleteDetector::MismatchResult
analyzeMemberExpr(const MemberExpr * ME)3428 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3429 assert(ME != nullptr && "Expected a member expression");
3430 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3431 return analyzeField(F, IsArrayForm);
3432 return NoMismatch;
3433 }
3434
hasMatchingVarInit(const DeclRefExpr * D)3435 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3436 const CXXNewExpr *NE = nullptr;
3437 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3438 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3439 NE->isArray() != IsArrayForm) {
3440 NewExprs.push_back(NE);
3441 }
3442 }
3443 return NewExprs.empty();
3444 }
3445
3446 static void
DiagnoseMismatchedNewDelete(Sema & SemaRef,SourceLocation DeleteLoc,const MismatchingNewDeleteDetector & Detector)3447 DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3448 const MismatchingNewDeleteDetector &Detector) {
3449 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3450 FixItHint H;
3451 if (!Detector.IsArrayForm)
3452 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3453 else {
3454 SourceLocation RSquare = Lexer::findLocationAfterToken(
3455 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3456 SemaRef.getLangOpts(), true);
3457 if (RSquare.isValid())
3458 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3459 }
3460 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3461 << Detector.IsArrayForm << H;
3462
3463 for (const auto *NE : Detector.NewExprs)
3464 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3465 << Detector.IsArrayForm;
3466 }
3467
AnalyzeDeleteExprMismatch(const CXXDeleteExpr * DE)3468 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3469 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3470 return;
3471 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3472 switch (Detector.analyzeDeleteExpr(DE)) {
3473 case MismatchingNewDeleteDetector::VarInitMismatches:
3474 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3475 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3476 break;
3477 }
3478 case MismatchingNewDeleteDetector::AnalyzeLater: {
3479 DeleteExprs[Detector.Field].push_back(
3480 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3481 break;
3482 }
3483 case MismatchingNewDeleteDetector::NoMismatch:
3484 break;
3485 }
3486 }
3487
AnalyzeDeleteExprMismatch(FieldDecl * Field,SourceLocation DeleteLoc,bool DeleteWasArrayForm)3488 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3489 bool DeleteWasArrayForm) {
3490 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3491 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3492 case MismatchingNewDeleteDetector::VarInitMismatches:
3493 llvm_unreachable("This analysis should have been done for class members.");
3494 case MismatchingNewDeleteDetector::AnalyzeLater:
3495 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3496 "translation unit.");
3497 case MismatchingNewDeleteDetector::MemberInitMismatches:
3498 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3499 break;
3500 case MismatchingNewDeleteDetector::NoMismatch:
3501 break;
3502 }
3503 }
3504
3505 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3506 /// @code ::delete ptr; @endcode
3507 /// or
3508 /// @code delete [] ptr; @endcode
3509 ExprResult
ActOnCXXDelete(SourceLocation StartLoc,bool UseGlobal,bool ArrayForm,Expr * ExE)3510 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3511 bool ArrayForm, Expr *ExE) {
3512 // C++ [expr.delete]p1:
3513 // The operand shall have a pointer type, or a class type having a single
3514 // non-explicit conversion function to a pointer type. The result has type
3515 // void.
3516 //
3517 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3518
3519 ExprResult Ex = ExE;
3520 FunctionDecl *OperatorDelete = nullptr;
3521 bool ArrayFormAsWritten = ArrayForm;
3522 bool UsualArrayDeleteWantsSize = false;
3523
3524 if (!Ex.get()->isTypeDependent()) {
3525 // Perform lvalue-to-rvalue cast, if needed.
3526 Ex = DefaultLvalueConversion(Ex.get());
3527 if (Ex.isInvalid())
3528 return ExprError();
3529
3530 QualType Type = Ex.get()->getType();
3531
3532 class DeleteConverter : public ContextualImplicitConverter {
3533 public:
3534 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3535
3536 bool match(QualType ConvType) override {
3537 // FIXME: If we have an operator T* and an operator void*, we must pick
3538 // the operator T*.
3539 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3540 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3541 return true;
3542 return false;
3543 }
3544
3545 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3546 QualType T) override {
3547 return S.Diag(Loc, diag::err_delete_operand) << T;
3548 }
3549
3550 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3551 QualType T) override {
3552 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3553 }
3554
3555 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3556 QualType T,
3557 QualType ConvTy) override {
3558 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3559 }
3560
3561 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3562 QualType ConvTy) override {
3563 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3564 << ConvTy;
3565 }
3566
3567 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3568 QualType T) override {
3569 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3570 }
3571
3572 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3573 QualType ConvTy) override {
3574 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3575 << ConvTy;
3576 }
3577
3578 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3579 QualType T,
3580 QualType ConvTy) override {
3581 llvm_unreachable("conversion functions are permitted");
3582 }
3583 } Converter;
3584
3585 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3586 if (Ex.isInvalid())
3587 return ExprError();
3588 Type = Ex.get()->getType();
3589 if (!Converter.match(Type))
3590 // FIXME: PerformContextualImplicitConversion should return ExprError
3591 // itself in this case.
3592 return ExprError();
3593
3594 QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3595 QualType PointeeElem = Context.getBaseElementType(Pointee);
3596
3597 if (Pointee.getAddressSpace() != LangAS::Default &&
3598 !getLangOpts().OpenCLCPlusPlus)
3599 return Diag(Ex.get()->getBeginLoc(),
3600 diag::err_address_space_qualified_delete)
3601 << Pointee.getUnqualifiedType()
3602 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3603
3604 CXXRecordDecl *PointeeRD = nullptr;
3605 if (Pointee->isVoidType() && !isSFINAEContext()) {
3606 // The C++ standard bans deleting a pointer to a non-object type, which
3607 // effectively bans deletion of "void*". However, most compilers support
3608 // this, so we treat it as a warning unless we're in a SFINAE context.
3609 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3610 << Type << Ex.get()->getSourceRange();
3611 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3612 Pointee->isSizelessType()) {
3613 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3614 << Type << Ex.get()->getSourceRange());
3615 } else if (!Pointee->isDependentType()) {
3616 // FIXME: This can result in errors if the definition was imported from a
3617 // module but is hidden.
3618 if (!RequireCompleteType(StartLoc, Pointee,
3619 diag::warn_delete_incomplete, Ex.get())) {
3620 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3621 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3622 }
3623 }
3624
3625 if (Pointee->isArrayType() && !ArrayForm) {
3626 Diag(StartLoc, diag::warn_delete_array_type)
3627 << Type << Ex.get()->getSourceRange()
3628 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3629 ArrayForm = true;
3630 }
3631
3632 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3633 ArrayForm ? OO_Array_Delete : OO_Delete);
3634
3635 if (PointeeRD) {
3636 if (!UseGlobal &&
3637 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3638 OperatorDelete))
3639 return ExprError();
3640
3641 // If we're allocating an array of records, check whether the
3642 // usual operator delete[] has a size_t parameter.
3643 if (ArrayForm) {
3644 // If the user specifically asked to use the global allocator,
3645 // we'll need to do the lookup into the class.
3646 if (UseGlobal)
3647 UsualArrayDeleteWantsSize =
3648 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3649
3650 // Otherwise, the usual operator delete[] should be the
3651 // function we just found.
3652 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3653 UsualArrayDeleteWantsSize =
3654 UsualDeallocFnInfo(*this,
3655 DeclAccessPair::make(OperatorDelete, AS_public))
3656 .HasSizeT;
3657 }
3658
3659 if (!PointeeRD->hasIrrelevantDestructor())
3660 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3661 MarkFunctionReferenced(StartLoc,
3662 const_cast<CXXDestructorDecl*>(Dtor));
3663 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3664 return ExprError();
3665 }
3666
3667 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3668 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3669 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3670 SourceLocation());
3671 }
3672
3673 if (!OperatorDelete) {
3674 if (getLangOpts().OpenCLCPlusPlus) {
3675 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3676 return ExprError();
3677 }
3678
3679 bool IsComplete = isCompleteType(StartLoc, Pointee);
3680 bool CanProvideSize =
3681 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3682 Pointee.isDestructedType());
3683 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3684
3685 // Look for a global declaration.
3686 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3687 Overaligned, DeleteName);
3688 }
3689
3690 MarkFunctionReferenced(StartLoc, OperatorDelete);
3691
3692 // Check access and ambiguity of destructor if we're going to call it.
3693 // Note that this is required even for a virtual delete.
3694 bool IsVirtualDelete = false;
3695 if (PointeeRD) {
3696 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3697 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3698 PDiag(diag::err_access_dtor) << PointeeElem);
3699 IsVirtualDelete = Dtor->isVirtual();
3700 }
3701 }
3702
3703 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3704
3705 // Convert the operand to the type of the first parameter of operator
3706 // delete. This is only necessary if we selected a destroying operator
3707 // delete that we are going to call (non-virtually); converting to void*
3708 // is trivial and left to AST consumers to handle.
3709 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3710 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3711 Qualifiers Qs = Pointee.getQualifiers();
3712 if (Qs.hasCVRQualifiers()) {
3713 // Qualifiers are irrelevant to this conversion; we're only looking
3714 // for access and ambiguity.
3715 Qs.removeCVRQualifiers();
3716 QualType Unqual = Context.getPointerType(
3717 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3718 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3719 }
3720 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3721 if (Ex.isInvalid())
3722 return ExprError();
3723 }
3724 }
3725
3726 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3727 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3728 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3729 AnalyzeDeleteExprMismatch(Result);
3730 return Result;
3731 }
3732
resolveBuiltinNewDeleteOverload(Sema & S,CallExpr * TheCall,bool IsDelete,FunctionDecl * & Operator)3733 static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3734 bool IsDelete,
3735 FunctionDecl *&Operator) {
3736
3737 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3738 IsDelete ? OO_Delete : OO_New);
3739
3740 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3741 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3742 assert(!R.empty() && "implicitly declared allocation functions not found");
3743 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3744
3745 // We do our own custom access checks below.
3746 R.suppressDiagnostics();
3747
3748 SmallVector<Expr *, 8> Args(TheCall->arguments());
3749 OverloadCandidateSet Candidates(R.getNameLoc(),
3750 OverloadCandidateSet::CSK_Normal);
3751 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3752 FnOvl != FnOvlEnd; ++FnOvl) {
3753 // Even member operator new/delete are implicitly treated as
3754 // static, so don't use AddMemberCandidate.
3755 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3756
3757 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3758 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3759 /*ExplicitTemplateArgs=*/nullptr, Args,
3760 Candidates,
3761 /*SuppressUserConversions=*/false);
3762 continue;
3763 }
3764
3765 FunctionDecl *Fn = cast<FunctionDecl>(D);
3766 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3767 /*SuppressUserConversions=*/false);
3768 }
3769
3770 SourceRange Range = TheCall->getSourceRange();
3771
3772 // Do the resolution.
3773 OverloadCandidateSet::iterator Best;
3774 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3775 case OR_Success: {
3776 // Got one!
3777 FunctionDecl *FnDecl = Best->Function;
3778 assert(R.getNamingClass() == nullptr &&
3779 "class members should not be considered");
3780
3781 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3782 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3783 << (IsDelete ? 1 : 0) << Range;
3784 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3785 << R.getLookupName() << FnDecl->getSourceRange();
3786 return true;
3787 }
3788
3789 Operator = FnDecl;
3790 return false;
3791 }
3792
3793 case OR_No_Viable_Function:
3794 Candidates.NoteCandidates(
3795 PartialDiagnosticAt(R.getNameLoc(),
3796 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3797 << R.getLookupName() << Range),
3798 S, OCD_AllCandidates, Args);
3799 return true;
3800
3801 case OR_Ambiguous:
3802 Candidates.NoteCandidates(
3803 PartialDiagnosticAt(R.getNameLoc(),
3804 S.PDiag(diag::err_ovl_ambiguous_call)
3805 << R.getLookupName() << Range),
3806 S, OCD_AmbiguousCandidates, Args);
3807 return true;
3808
3809 case OR_Deleted: {
3810 Candidates.NoteCandidates(
3811 PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3812 << R.getLookupName() << Range),
3813 S, OCD_AllCandidates, Args);
3814 return true;
3815 }
3816 }
3817 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3818 }
3819
3820 ExprResult
SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,bool IsDelete)3821 Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3822 bool IsDelete) {
3823 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3824 if (!getLangOpts().CPlusPlus) {
3825 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3826 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3827 << "C++";
3828 return ExprError();
3829 }
3830 // CodeGen assumes it can find the global new and delete to call,
3831 // so ensure that they are declared.
3832 DeclareGlobalNewDelete();
3833
3834 FunctionDecl *OperatorNewOrDelete = nullptr;
3835 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3836 OperatorNewOrDelete))
3837 return ExprError();
3838 assert(OperatorNewOrDelete && "should be found");
3839
3840 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3841 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3842
3843 TheCall->setType(OperatorNewOrDelete->getReturnType());
3844 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3845 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3846 InitializedEntity Entity =
3847 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3848 ExprResult Arg = PerformCopyInitialization(
3849 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3850 if (Arg.isInvalid())
3851 return ExprError();
3852 TheCall->setArg(i, Arg.get());
3853 }
3854 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3855 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3856 "Callee expected to be implicit cast to a builtin function pointer");
3857 Callee->setType(OperatorNewOrDelete->getType());
3858
3859 return TheCallResult;
3860 }
3861
CheckVirtualDtorCall(CXXDestructorDecl * dtor,SourceLocation Loc,bool IsDelete,bool CallCanBeVirtual,bool WarnOnNonAbstractTypes,SourceLocation DtorLoc)3862 void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3863 bool IsDelete, bool CallCanBeVirtual,
3864 bool WarnOnNonAbstractTypes,
3865 SourceLocation DtorLoc) {
3866 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3867 return;
3868
3869 // C++ [expr.delete]p3:
3870 // In the first alternative (delete object), if the static type of the
3871 // object to be deleted is different from its dynamic type, the static
3872 // type shall be a base class of the dynamic type of the object to be
3873 // deleted and the static type shall have a virtual destructor or the
3874 // behavior is undefined.
3875 //
3876 const CXXRecordDecl *PointeeRD = dtor->getParent();
3877 // Note: a final class cannot be derived from, no issue there
3878 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3879 return;
3880
3881 // If the superclass is in a system header, there's nothing that can be done.
3882 // The `delete` (where we emit the warning) can be in a system header,
3883 // what matters for this warning is where the deleted type is defined.
3884 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3885 return;
3886
3887 QualType ClassType = dtor->getThisType()->getPointeeType();
3888 if (PointeeRD->isAbstract()) {
3889 // If the class is abstract, we warn by default, because we're
3890 // sure the code has undefined behavior.
3891 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3892 << ClassType;
3893 } else if (WarnOnNonAbstractTypes) {
3894 // Otherwise, if this is not an array delete, it's a bit suspect,
3895 // but not necessarily wrong.
3896 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3897 << ClassType;
3898 }
3899 if (!IsDelete) {
3900 std::string TypeStr;
3901 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3902 Diag(DtorLoc, diag::note_delete_non_virtual)
3903 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3904 }
3905 }
3906
ActOnConditionVariable(Decl * ConditionVar,SourceLocation StmtLoc,ConditionKind CK)3907 Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3908 SourceLocation StmtLoc,
3909 ConditionKind CK) {
3910 ExprResult E =
3911 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3912 if (E.isInvalid())
3913 return ConditionError();
3914 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3915 CK == ConditionKind::ConstexprIf);
3916 }
3917
3918 /// Check the use of the given variable as a C++ condition in an if,
3919 /// while, do-while, or switch statement.
CheckConditionVariable(VarDecl * ConditionVar,SourceLocation StmtLoc,ConditionKind CK)3920 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3921 SourceLocation StmtLoc,
3922 ConditionKind CK) {
3923 if (ConditionVar->isInvalidDecl())
3924 return ExprError();
3925
3926 QualType T = ConditionVar->getType();
3927
3928 // C++ [stmt.select]p2:
3929 // The declarator shall not specify a function or an array.
3930 if (T->isFunctionType())
3931 return ExprError(Diag(ConditionVar->getLocation(),
3932 diag::err_invalid_use_of_function_type)
3933 << ConditionVar->getSourceRange());
3934 else if (T->isArrayType())
3935 return ExprError(Diag(ConditionVar->getLocation(),
3936 diag::err_invalid_use_of_array_type)
3937 << ConditionVar->getSourceRange());
3938
3939 ExprResult Condition = BuildDeclRefExpr(
3940 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3941 ConditionVar->getLocation());
3942
3943 switch (CK) {
3944 case ConditionKind::Boolean:
3945 return CheckBooleanCondition(StmtLoc, Condition.get());
3946
3947 case ConditionKind::ConstexprIf:
3948 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3949
3950 case ConditionKind::Switch:
3951 return CheckSwitchCondition(StmtLoc, Condition.get());
3952 }
3953
3954 llvm_unreachable("unexpected condition kind");
3955 }
3956
3957 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
CheckCXXBooleanCondition(Expr * CondExpr,bool IsConstexpr)3958 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3959 // C++11 6.4p4:
3960 // The value of a condition that is an initialized declaration in a statement
3961 // other than a switch statement is the value of the declared variable
3962 // implicitly converted to type bool. If that conversion is ill-formed, the
3963 // program is ill-formed.
3964 // The value of a condition that is an expression is the value of the
3965 // expression, implicitly converted to bool.
3966 //
3967 // C++2b 8.5.2p2
3968 // If the if statement is of the form if constexpr, the value of the condition
3969 // is contextually converted to bool and the converted expression shall be
3970 // a constant expression.
3971 //
3972
3973 ExprResult E = PerformContextuallyConvertToBool(CondExpr);
3974 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
3975 return E;
3976
3977 // FIXME: Return this value to the caller so they don't need to recompute it.
3978 llvm::APSInt Cond;
3979 E = VerifyIntegerConstantExpression(
3980 E.get(), &Cond,
3981 diag::err_constexpr_if_condition_expression_is_not_constant);
3982 return E;
3983 }
3984
3985 /// Helper function to determine whether this is the (deprecated) C++
3986 /// conversion from a string literal to a pointer to non-const char or
3987 /// non-const wchar_t (for narrow and wide string literals,
3988 /// respectively).
3989 bool
IsStringLiteralToNonConstPointerConversion(Expr * From,QualType ToType)3990 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3991 // Look inside the implicit cast, if it exists.
3992 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3993 From = Cast->getSubExpr();
3994
3995 // A string literal (2.13.4) that is not a wide string literal can
3996 // be converted to an rvalue of type "pointer to char"; a wide
3997 // string literal can be converted to an rvalue of type "pointer
3998 // to wchar_t" (C++ 4.2p2).
3999 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4000 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4001 if (const BuiltinType *ToPointeeType
4002 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4003 // This conversion is considered only when there is an
4004 // explicit appropriate pointer target type (C++ 4.2p2).
4005 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4006 switch (StrLit->getKind()) {
4007 case StringLiteral::UTF8:
4008 case StringLiteral::UTF16:
4009 case StringLiteral::UTF32:
4010 // We don't allow UTF literals to be implicitly converted
4011 break;
4012 case StringLiteral::Ordinary:
4013 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4014 ToPointeeType->getKind() == BuiltinType::Char_S);
4015 case StringLiteral::Wide:
4016 return Context.typesAreCompatible(Context.getWideCharType(),
4017 QualType(ToPointeeType, 0));
4018 }
4019 }
4020 }
4021
4022 return false;
4023 }
4024
BuildCXXCastArgument(Sema & S,SourceLocation CastLoc,QualType Ty,CastKind Kind,CXXMethodDecl * Method,DeclAccessPair FoundDecl,bool HadMultipleCandidates,Expr * From)4025 static ExprResult BuildCXXCastArgument(Sema &S,
4026 SourceLocation CastLoc,
4027 QualType Ty,
4028 CastKind Kind,
4029 CXXMethodDecl *Method,
4030 DeclAccessPair FoundDecl,
4031 bool HadMultipleCandidates,
4032 Expr *From) {
4033 switch (Kind) {
4034 default: llvm_unreachable("Unhandled cast kind!");
4035 case CK_ConstructorConversion: {
4036 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4037 SmallVector<Expr*, 8> ConstructorArgs;
4038
4039 if (S.RequireNonAbstractType(CastLoc, Ty,
4040 diag::err_allocation_of_abstract_type))
4041 return ExprError();
4042
4043 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4044 ConstructorArgs))
4045 return ExprError();
4046
4047 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4048 InitializedEntity::InitializeTemporary(Ty));
4049 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4050 return ExprError();
4051
4052 ExprResult Result = S.BuildCXXConstructExpr(
4053 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4054 ConstructorArgs, HadMultipleCandidates,
4055 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4056 CXXConstructExpr::CK_Complete, SourceRange());
4057 if (Result.isInvalid())
4058 return ExprError();
4059
4060 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4061 }
4062
4063 case CK_UserDefinedConversion: {
4064 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4065
4066 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4067 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4068 return ExprError();
4069
4070 // Create an implicit call expr that calls it.
4071 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4072 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4073 HadMultipleCandidates);
4074 if (Result.isInvalid())
4075 return ExprError();
4076 // Record usage of conversion in an implicit cast.
4077 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4078 CK_UserDefinedConversion, Result.get(),
4079 nullptr, Result.get()->getValueKind(),
4080 S.CurFPFeatureOverrides());
4081
4082 return S.MaybeBindToTemporary(Result.get());
4083 }
4084 }
4085 }
4086
4087 /// PerformImplicitConversion - Perform an implicit conversion of the
4088 /// expression From to the type ToType using the pre-computed implicit
4089 /// conversion sequence ICS. Returns the converted
4090 /// expression. Action is the kind of conversion we're performing,
4091 /// used in the error message.
4092 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,const ImplicitConversionSequence & ICS,AssignmentAction Action,CheckedConversionKind CCK)4093 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4094 const ImplicitConversionSequence &ICS,
4095 AssignmentAction Action,
4096 CheckedConversionKind CCK) {
4097 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4098 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
4099 return From;
4100
4101 switch (ICS.getKind()) {
4102 case ImplicitConversionSequence::StandardConversion: {
4103 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4104 Action, CCK);
4105 if (Res.isInvalid())
4106 return ExprError();
4107 From = Res.get();
4108 break;
4109 }
4110
4111 case ImplicitConversionSequence::UserDefinedConversion: {
4112
4113 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
4114 CastKind CastKind;
4115 QualType BeforeToType;
4116 assert(FD && "no conversion function for user-defined conversion seq");
4117 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4118 CastKind = CK_UserDefinedConversion;
4119
4120 // If the user-defined conversion is specified by a conversion function,
4121 // the initial standard conversion sequence converts the source type to
4122 // the implicit object parameter of the conversion function.
4123 BeforeToType = Context.getTagDeclType(Conv->getParent());
4124 } else {
4125 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4126 CastKind = CK_ConstructorConversion;
4127 // Do no conversion if dealing with ... for the first conversion.
4128 if (!ICS.UserDefined.EllipsisConversion) {
4129 // If the user-defined conversion is specified by a constructor, the
4130 // initial standard conversion sequence converts the source type to
4131 // the type required by the argument of the constructor
4132 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4133 }
4134 }
4135 // Watch out for ellipsis conversion.
4136 if (!ICS.UserDefined.EllipsisConversion) {
4137 ExprResult Res =
4138 PerformImplicitConversion(From, BeforeToType,
4139 ICS.UserDefined.Before, AA_Converting,
4140 CCK);
4141 if (Res.isInvalid())
4142 return ExprError();
4143 From = Res.get();
4144 }
4145
4146 ExprResult CastArg = BuildCXXCastArgument(
4147 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4148 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4149 ICS.UserDefined.HadMultipleCandidates, From);
4150
4151 if (CastArg.isInvalid())
4152 return ExprError();
4153
4154 From = CastArg.get();
4155
4156 // C++ [over.match.oper]p7:
4157 // [...] the second standard conversion sequence of a user-defined
4158 // conversion sequence is not applied.
4159 if (CCK == CCK_ForBuiltinOverloadedOp)
4160 return From;
4161
4162 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4163 AA_Converting, CCK);
4164 }
4165
4166 case ImplicitConversionSequence::AmbiguousConversion:
4167 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4168 PDiag(diag::err_typecheck_ambiguous_condition)
4169 << From->getSourceRange());
4170 return ExprError();
4171
4172 case ImplicitConversionSequence::EllipsisConversion:
4173 llvm_unreachable("Cannot perform an ellipsis conversion");
4174
4175 case ImplicitConversionSequence::BadConversion:
4176 Sema::AssignConvertType ConvTy =
4177 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4178 bool Diagnosed = DiagnoseAssignmentResult(
4179 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4180 ToType, From->getType(), From, Action);
4181 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4182 return ExprError();
4183 }
4184
4185 // Everything went well.
4186 return From;
4187 }
4188
4189 /// PerformImplicitConversion - Perform an implicit conversion of the
4190 /// expression From to the type ToType by following the standard
4191 /// conversion sequence SCS. Returns the converted
4192 /// expression. Flavor is the context in which we're performing this
4193 /// conversion, for use in error messages.
4194 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,const StandardConversionSequence & SCS,AssignmentAction Action,CheckedConversionKind CCK)4195 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4196 const StandardConversionSequence& SCS,
4197 AssignmentAction Action,
4198 CheckedConversionKind CCK) {
4199 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
4200
4201 // Overall FIXME: we are recomputing too many types here and doing far too
4202 // much extra work. What this means is that we need to keep track of more
4203 // information that is computed when we try the implicit conversion initially,
4204 // so that we don't need to recompute anything here.
4205 QualType FromType = From->getType();
4206
4207 if (SCS.CopyConstructor) {
4208 // FIXME: When can ToType be a reference type?
4209 assert(!ToType->isReferenceType());
4210 if (SCS.Second == ICK_Derived_To_Base) {
4211 SmallVector<Expr*, 8> ConstructorArgs;
4212 if (CompleteConstructorCall(
4213 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4214 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4215 return ExprError();
4216 return BuildCXXConstructExpr(
4217 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4218 SCS.FoundCopyConstructor, SCS.CopyConstructor,
4219 ConstructorArgs, /*HadMultipleCandidates*/ false,
4220 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4221 CXXConstructExpr::CK_Complete, SourceRange());
4222 }
4223 return BuildCXXConstructExpr(
4224 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4225 SCS.FoundCopyConstructor, SCS.CopyConstructor,
4226 From, /*HadMultipleCandidates*/ false,
4227 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4228 CXXConstructExpr::CK_Complete, SourceRange());
4229 }
4230
4231 // Resolve overloaded function references.
4232 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4233 DeclAccessPair Found;
4234 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
4235 true, Found);
4236 if (!Fn)
4237 return ExprError();
4238
4239 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4240 return ExprError();
4241
4242 From = FixOverloadedFunctionReference(From, Found, Fn);
4243
4244 // We might get back another placeholder expression if we resolved to a
4245 // builtin.
4246 ExprResult Checked = CheckPlaceholderExpr(From);
4247 if (Checked.isInvalid())
4248 return ExprError();
4249
4250 From = Checked.get();
4251 FromType = From->getType();
4252 }
4253
4254 // If we're converting to an atomic type, first convert to the corresponding
4255 // non-atomic type.
4256 QualType ToAtomicType;
4257 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4258 ToAtomicType = ToType;
4259 ToType = ToAtomic->getValueType();
4260 }
4261
4262 QualType InitialFromType = FromType;
4263 // Perform the first implicit conversion.
4264 switch (SCS.First) {
4265 case ICK_Identity:
4266 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4267 FromType = FromAtomic->getValueType().getUnqualifiedType();
4268 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4269 From, /*BasePath=*/nullptr, VK_PRValue,
4270 FPOptionsOverride());
4271 }
4272 break;
4273
4274 case ICK_Lvalue_To_Rvalue: {
4275 assert(From->getObjectKind() != OK_ObjCProperty);
4276 ExprResult FromRes = DefaultLvalueConversion(From);
4277 if (FromRes.isInvalid())
4278 return ExprError();
4279
4280 From = FromRes.get();
4281 FromType = From->getType();
4282 break;
4283 }
4284
4285 case ICK_Array_To_Pointer:
4286 FromType = Context.getArrayDecayedType(FromType);
4287 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4288 /*BasePath=*/nullptr, CCK)
4289 .get();
4290 break;
4291
4292 case ICK_Function_To_Pointer:
4293 FromType = Context.getPointerType(FromType);
4294 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4295 VK_PRValue, /*BasePath=*/nullptr, CCK)
4296 .get();
4297 break;
4298
4299 default:
4300 llvm_unreachable("Improper first standard conversion");
4301 }
4302
4303 // Perform the second implicit conversion
4304 switch (SCS.Second) {
4305 case ICK_Identity:
4306 // C++ [except.spec]p5:
4307 // [For] assignment to and initialization of pointers to functions,
4308 // pointers to member functions, and references to functions: the
4309 // target entity shall allow at least the exceptions allowed by the
4310 // source value in the assignment or initialization.
4311 switch (Action) {
4312 case AA_Assigning:
4313 case AA_Initializing:
4314 // Note, function argument passing and returning are initialization.
4315 case AA_Passing:
4316 case AA_Returning:
4317 case AA_Sending:
4318 case AA_Passing_CFAudited:
4319 if (CheckExceptionSpecCompatibility(From, ToType))
4320 return ExprError();
4321 break;
4322
4323 case AA_Casting:
4324 case AA_Converting:
4325 // Casts and implicit conversions are not initialization, so are not
4326 // checked for exception specification mismatches.
4327 break;
4328 }
4329 // Nothing else to do.
4330 break;
4331
4332 case ICK_Integral_Promotion:
4333 case ICK_Integral_Conversion:
4334 if (ToType->isBooleanType()) {
4335 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4336 SCS.Second == ICK_Integral_Promotion &&
4337 "only enums with fixed underlying type can promote to bool");
4338 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
4339 /*BasePath=*/nullptr, CCK)
4340 .get();
4341 } else {
4342 From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
4343 /*BasePath=*/nullptr, CCK)
4344 .get();
4345 }
4346 break;
4347
4348 case ICK_Floating_Promotion:
4349 case ICK_Floating_Conversion:
4350 From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
4351 /*BasePath=*/nullptr, CCK)
4352 .get();
4353 break;
4354
4355 case ICK_Complex_Promotion:
4356 case ICK_Complex_Conversion: {
4357 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4358 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4359 CastKind CK;
4360 if (FromEl->isRealFloatingType()) {
4361 if (ToEl->isRealFloatingType())
4362 CK = CK_FloatingComplexCast;
4363 else
4364 CK = CK_FloatingComplexToIntegralComplex;
4365 } else if (ToEl->isRealFloatingType()) {
4366 CK = CK_IntegralComplexToFloatingComplex;
4367 } else {
4368 CK = CK_IntegralComplexCast;
4369 }
4370 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4371 CCK)
4372 .get();
4373 break;
4374 }
4375
4376 case ICK_Floating_Integral:
4377 if (ToType->isRealFloatingType())
4378 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
4379 /*BasePath=*/nullptr, CCK)
4380 .get();
4381 else
4382 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
4383 /*BasePath=*/nullptr, CCK)
4384 .get();
4385 break;
4386
4387 case ICK_Compatible_Conversion:
4388 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4389 /*BasePath=*/nullptr, CCK).get();
4390 break;
4391
4392 case ICK_Writeback_Conversion:
4393 case ICK_Pointer_Conversion: {
4394 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4395 // Diagnose incompatible Objective-C conversions
4396 if (Action == AA_Initializing || Action == AA_Assigning)
4397 Diag(From->getBeginLoc(),
4398 diag::ext_typecheck_convert_incompatible_pointer)
4399 << ToType << From->getType() << Action << From->getSourceRange()
4400 << 0;
4401 else
4402 Diag(From->getBeginLoc(),
4403 diag::ext_typecheck_convert_incompatible_pointer)
4404 << From->getType() << ToType << Action << From->getSourceRange()
4405 << 0;
4406
4407 if (From->getType()->isObjCObjectPointerType() &&
4408 ToType->isObjCObjectPointerType())
4409 EmitRelatedResultTypeNote(From);
4410 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4411 !CheckObjCARCUnavailableWeakConversion(ToType,
4412 From->getType())) {
4413 if (Action == AA_Initializing)
4414 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4415 else
4416 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4417 << (Action == AA_Casting) << From->getType() << ToType
4418 << From->getSourceRange();
4419 }
4420
4421 // Defer address space conversion to the third conversion.
4422 QualType FromPteeType = From->getType()->getPointeeType();
4423 QualType ToPteeType = ToType->getPointeeType();
4424 QualType NewToType = ToType;
4425 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4426 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4427 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4428 NewToType = Context.getAddrSpaceQualType(NewToType,
4429 FromPteeType.getAddressSpace());
4430 if (ToType->isObjCObjectPointerType())
4431 NewToType = Context.getObjCObjectPointerType(NewToType);
4432 else if (ToType->isBlockPointerType())
4433 NewToType = Context.getBlockPointerType(NewToType);
4434 else
4435 NewToType = Context.getPointerType(NewToType);
4436 }
4437
4438 CastKind Kind;
4439 CXXCastPath BasePath;
4440 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4441 return ExprError();
4442
4443 // Make sure we extend blocks if necessary.
4444 // FIXME: doing this here is really ugly.
4445 if (Kind == CK_BlockPointerToObjCPointerCast) {
4446 ExprResult E = From;
4447 (void) PrepareCastToObjCObjectPointer(E);
4448 From = E.get();
4449 }
4450 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4451 CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4452 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4453 .get();
4454 break;
4455 }
4456
4457 case ICK_Pointer_Member: {
4458 CastKind Kind;
4459 CXXCastPath BasePath;
4460 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4461 return ExprError();
4462 if (CheckExceptionSpecCompatibility(From, ToType))
4463 return ExprError();
4464
4465 // We may not have been able to figure out what this member pointer resolved
4466 // to up until this exact point. Attempt to lock-in it's inheritance model.
4467 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4468 (void)isCompleteType(From->getExprLoc(), From->getType());
4469 (void)isCompleteType(From->getExprLoc(), ToType);
4470 }
4471
4472 From =
4473 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4474 break;
4475 }
4476
4477 case ICK_Boolean_Conversion:
4478 // Perform half-to-boolean conversion via float.
4479 if (From->getType()->isHalfType()) {
4480 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4481 FromType = Context.FloatTy;
4482 }
4483
4484 From = ImpCastExprToType(From, Context.BoolTy,
4485 ScalarTypeToBooleanCastKind(FromType), VK_PRValue,
4486 /*BasePath=*/nullptr, CCK)
4487 .get();
4488 break;
4489
4490 case ICK_Derived_To_Base: {
4491 CXXCastPath BasePath;
4492 if (CheckDerivedToBaseConversion(
4493 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4494 From->getSourceRange(), &BasePath, CStyle))
4495 return ExprError();
4496
4497 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4498 CK_DerivedToBase, From->getValueKind(),
4499 &BasePath, CCK).get();
4500 break;
4501 }
4502
4503 case ICK_Vector_Conversion:
4504 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4505 /*BasePath=*/nullptr, CCK)
4506 .get();
4507 break;
4508
4509 case ICK_SVE_Vector_Conversion:
4510 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4511 /*BasePath=*/nullptr, CCK)
4512 .get();
4513 break;
4514
4515 case ICK_Vector_Splat: {
4516 // Vector splat from any arithmetic type to a vector.
4517 Expr *Elem = prepareVectorSplat(ToType, From).get();
4518 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4519 /*BasePath=*/nullptr, CCK)
4520 .get();
4521 break;
4522 }
4523
4524 case ICK_Complex_Real:
4525 // Case 1. x -> _Complex y
4526 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4527 QualType ElType = ToComplex->getElementType();
4528 bool isFloatingComplex = ElType->isRealFloatingType();
4529
4530 // x -> y
4531 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4532 // do nothing
4533 } else if (From->getType()->isRealFloatingType()) {
4534 From = ImpCastExprToType(From, ElType,
4535 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4536 } else {
4537 assert(From->getType()->isIntegerType());
4538 From = ImpCastExprToType(From, ElType,
4539 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4540 }
4541 // y -> _Complex y
4542 From = ImpCastExprToType(From, ToType,
4543 isFloatingComplex ? CK_FloatingRealToComplex
4544 : CK_IntegralRealToComplex).get();
4545
4546 // Case 2. _Complex x -> y
4547 } else {
4548 auto *FromComplex = From->getType()->castAs<ComplexType>();
4549 QualType ElType = FromComplex->getElementType();
4550 bool isFloatingComplex = ElType->isRealFloatingType();
4551
4552 // _Complex x -> x
4553 From = ImpCastExprToType(From, ElType,
4554 isFloatingComplex ? CK_FloatingComplexToReal
4555 : CK_IntegralComplexToReal,
4556 VK_PRValue, /*BasePath=*/nullptr, CCK)
4557 .get();
4558
4559 // x -> y
4560 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4561 // do nothing
4562 } else if (ToType->isRealFloatingType()) {
4563 From = ImpCastExprToType(From, ToType,
4564 isFloatingComplex ? CK_FloatingCast
4565 : CK_IntegralToFloating,
4566 VK_PRValue, /*BasePath=*/nullptr, CCK)
4567 .get();
4568 } else {
4569 assert(ToType->isIntegerType());
4570 From = ImpCastExprToType(From, ToType,
4571 isFloatingComplex ? CK_FloatingToIntegral
4572 : CK_IntegralCast,
4573 VK_PRValue, /*BasePath=*/nullptr, CCK)
4574 .get();
4575 }
4576 }
4577 break;
4578
4579 case ICK_Block_Pointer_Conversion: {
4580 LangAS AddrSpaceL =
4581 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4582 LangAS AddrSpaceR =
4583 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4584 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4585 "Invalid cast");
4586 CastKind Kind =
4587 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4588 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4589 VK_PRValue, /*BasePath=*/nullptr, CCK)
4590 .get();
4591 break;
4592 }
4593
4594 case ICK_TransparentUnionConversion: {
4595 ExprResult FromRes = From;
4596 Sema::AssignConvertType ConvTy =
4597 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4598 if (FromRes.isInvalid())
4599 return ExprError();
4600 From = FromRes.get();
4601 assert ((ConvTy == Sema::Compatible) &&
4602 "Improper transparent union conversion");
4603 (void)ConvTy;
4604 break;
4605 }
4606
4607 case ICK_Zero_Event_Conversion:
4608 case ICK_Zero_Queue_Conversion:
4609 From = ImpCastExprToType(From, ToType,
4610 CK_ZeroToOCLOpaqueType,
4611 From->getValueKind()).get();
4612 break;
4613
4614 case ICK_Lvalue_To_Rvalue:
4615 case ICK_Array_To_Pointer:
4616 case ICK_Function_To_Pointer:
4617 case ICK_Function_Conversion:
4618 case ICK_Qualification:
4619 case ICK_Num_Conversion_Kinds:
4620 case ICK_C_Only_Conversion:
4621 case ICK_Incompatible_Pointer_Conversion:
4622 llvm_unreachable("Improper second standard conversion");
4623 }
4624
4625 switch (SCS.Third) {
4626 case ICK_Identity:
4627 // Nothing to do.
4628 break;
4629
4630 case ICK_Function_Conversion:
4631 // If both sides are functions (or pointers/references to them), there could
4632 // be incompatible exception declarations.
4633 if (CheckExceptionSpecCompatibility(From, ToType))
4634 return ExprError();
4635
4636 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4637 /*BasePath=*/nullptr, CCK)
4638 .get();
4639 break;
4640
4641 case ICK_Qualification: {
4642 ExprValueKind VK = From->getValueKind();
4643 CastKind CK = CK_NoOp;
4644
4645 if (ToType->isReferenceType() &&
4646 ToType->getPointeeType().getAddressSpace() !=
4647 From->getType().getAddressSpace())
4648 CK = CK_AddressSpaceConversion;
4649
4650 if (ToType->isPointerType() &&
4651 ToType->getPointeeType().getAddressSpace() !=
4652 From->getType()->getPointeeType().getAddressSpace())
4653 CK = CK_AddressSpaceConversion;
4654
4655 if (!isCast(CCK) &&
4656 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
4657 From->getType()->getPointeeType().getQualifiers().hasUnaligned()) {
4658 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
4659 << InitialFromType << ToType;
4660 }
4661
4662 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4663 /*BasePath=*/nullptr, CCK)
4664 .get();
4665
4666 if (SCS.DeprecatedStringLiteralToCharPtr &&
4667 !getLangOpts().WritableStrings) {
4668 Diag(From->getBeginLoc(),
4669 getLangOpts().CPlusPlus11
4670 ? diag::ext_deprecated_string_literal_conversion
4671 : diag::warn_deprecated_string_literal_conversion)
4672 << ToType.getNonReferenceType();
4673 }
4674
4675 break;
4676 }
4677
4678 default:
4679 llvm_unreachable("Improper third standard conversion");
4680 }
4681
4682 // If this conversion sequence involved a scalar -> atomic conversion, perform
4683 // that conversion now.
4684 if (!ToAtomicType.isNull()) {
4685 assert(Context.hasSameType(
4686 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4687 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4688 VK_PRValue, nullptr, CCK)
4689 .get();
4690 }
4691
4692 // Materialize a temporary if we're implicitly converting to a reference
4693 // type. This is not required by the C++ rules but is necessary to maintain
4694 // AST invariants.
4695 if (ToType->isReferenceType() && From->isPRValue()) {
4696 ExprResult Res = TemporaryMaterializationConversion(From);
4697 if (Res.isInvalid())
4698 return ExprError();
4699 From = Res.get();
4700 }
4701
4702 // If this conversion sequence succeeded and involved implicitly converting a
4703 // _Nullable type to a _Nonnull one, complain.
4704 if (!isCast(CCK))
4705 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4706 From->getBeginLoc());
4707
4708 return From;
4709 }
4710
4711 /// Check the completeness of a type in a unary type trait.
4712 ///
4713 /// If the particular type trait requires a complete type, tries to complete
4714 /// it. If completing the type fails, a diagnostic is emitted and false
4715 /// returned. If completing the type succeeds or no completion was required,
4716 /// returns true.
CheckUnaryTypeTraitTypeCompleteness(Sema & S,TypeTrait UTT,SourceLocation Loc,QualType ArgTy)4717 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4718 SourceLocation Loc,
4719 QualType ArgTy) {
4720 // C++0x [meta.unary.prop]p3:
4721 // For all of the class templates X declared in this Clause, instantiating
4722 // that template with a template argument that is a class template
4723 // specialization may result in the implicit instantiation of the template
4724 // argument if and only if the semantics of X require that the argument
4725 // must be a complete type.
4726 // We apply this rule to all the type trait expressions used to implement
4727 // these class templates. We also try to follow any GCC documented behavior
4728 // in these expressions to ensure portability of standard libraries.
4729 switch (UTT) {
4730 default: llvm_unreachable("not a UTT");
4731 // is_complete_type somewhat obviously cannot require a complete type.
4732 case UTT_IsCompleteType:
4733 // Fall-through
4734
4735 // These traits are modeled on the type predicates in C++0x
4736 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4737 // requiring a complete type, as whether or not they return true cannot be
4738 // impacted by the completeness of the type.
4739 case UTT_IsVoid:
4740 case UTT_IsIntegral:
4741 case UTT_IsFloatingPoint:
4742 case UTT_IsArray:
4743 case UTT_IsPointer:
4744 case UTT_IsLvalueReference:
4745 case UTT_IsRvalueReference:
4746 case UTT_IsMemberFunctionPointer:
4747 case UTT_IsMemberObjectPointer:
4748 case UTT_IsEnum:
4749 case UTT_IsUnion:
4750 case UTT_IsClass:
4751 case UTT_IsFunction:
4752 case UTT_IsReference:
4753 case UTT_IsArithmetic:
4754 case UTT_IsFundamental:
4755 case UTT_IsObject:
4756 case UTT_IsScalar:
4757 case UTT_IsCompound:
4758 case UTT_IsMemberPointer:
4759 // Fall-through
4760
4761 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4762 // which requires some of its traits to have the complete type. However,
4763 // the completeness of the type cannot impact these traits' semantics, and
4764 // so they don't require it. This matches the comments on these traits in
4765 // Table 49.
4766 case UTT_IsConst:
4767 case UTT_IsVolatile:
4768 case UTT_IsSigned:
4769 case UTT_IsUnsigned:
4770
4771 // This type trait always returns false, checking the type is moot.
4772 case UTT_IsInterfaceClass:
4773 return true;
4774
4775 // C++14 [meta.unary.prop]:
4776 // If T is a non-union class type, T shall be a complete type.
4777 case UTT_IsEmpty:
4778 case UTT_IsPolymorphic:
4779 case UTT_IsAbstract:
4780 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4781 if (!RD->isUnion())
4782 return !S.RequireCompleteType(
4783 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4784 return true;
4785
4786 // C++14 [meta.unary.prop]:
4787 // If T is a class type, T shall be a complete type.
4788 case UTT_IsFinal:
4789 case UTT_IsSealed:
4790 if (ArgTy->getAsCXXRecordDecl())
4791 return !S.RequireCompleteType(
4792 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4793 return true;
4794
4795 // C++1z [meta.unary.prop]:
4796 // remove_all_extents_t<T> shall be a complete type or cv void.
4797 case UTT_IsAggregate:
4798 case UTT_IsTrivial:
4799 case UTT_IsTriviallyCopyable:
4800 case UTT_IsStandardLayout:
4801 case UTT_IsPOD:
4802 case UTT_IsLiteral:
4803 // By analogy, is_trivially_relocatable imposes the same constraints.
4804 case UTT_IsTriviallyRelocatable:
4805 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4806 // or an array of unknown bound. But GCC actually imposes the same constraints
4807 // as above.
4808 case UTT_HasNothrowAssign:
4809 case UTT_HasNothrowMoveAssign:
4810 case UTT_HasNothrowConstructor:
4811 case UTT_HasNothrowCopy:
4812 case UTT_HasTrivialAssign:
4813 case UTT_HasTrivialMoveAssign:
4814 case UTT_HasTrivialDefaultConstructor:
4815 case UTT_HasTrivialMoveConstructor:
4816 case UTT_HasTrivialCopy:
4817 case UTT_HasTrivialDestructor:
4818 case UTT_HasVirtualDestructor:
4819 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4820 LLVM_FALLTHROUGH;
4821
4822 // C++1z [meta.unary.prop]:
4823 // T shall be a complete type, cv void, or an array of unknown bound.
4824 case UTT_IsDestructible:
4825 case UTT_IsNothrowDestructible:
4826 case UTT_IsTriviallyDestructible:
4827 case UTT_HasUniqueObjectRepresentations:
4828 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4829 return true;
4830
4831 return !S.RequireCompleteType(
4832 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4833 }
4834 }
4835
HasNoThrowOperator(const RecordType * RT,OverloadedOperatorKind Op,Sema & Self,SourceLocation KeyLoc,ASTContext & C,bool (CXXRecordDecl::* HasTrivial)()const,bool (CXXRecordDecl::* HasNonTrivial)()const,bool (CXXMethodDecl::* IsDesiredOp)()const)4836 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4837 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4838 bool (CXXRecordDecl::*HasTrivial)() const,
4839 bool (CXXRecordDecl::*HasNonTrivial)() const,
4840 bool (CXXMethodDecl::*IsDesiredOp)() const)
4841 {
4842 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4843 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4844 return true;
4845
4846 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4847 DeclarationNameInfo NameInfo(Name, KeyLoc);
4848 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4849 if (Self.LookupQualifiedName(Res, RD)) {
4850 bool FoundOperator = false;
4851 Res.suppressDiagnostics();
4852 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4853 Op != OpEnd; ++Op) {
4854 if (isa<FunctionTemplateDecl>(*Op))
4855 continue;
4856
4857 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4858 if((Operator->*IsDesiredOp)()) {
4859 FoundOperator = true;
4860 auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
4861 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4862 if (!CPT || !CPT->isNothrow())
4863 return false;
4864 }
4865 }
4866 return FoundOperator;
4867 }
4868 return false;
4869 }
4870
EvaluateUnaryTypeTrait(Sema & Self,TypeTrait UTT,SourceLocation KeyLoc,QualType T)4871 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4872 SourceLocation KeyLoc, QualType T) {
4873 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4874
4875 ASTContext &C = Self.Context;
4876 switch(UTT) {
4877 default: llvm_unreachable("not a UTT");
4878 // Type trait expressions corresponding to the primary type category
4879 // predicates in C++0x [meta.unary.cat].
4880 case UTT_IsVoid:
4881 return T->isVoidType();
4882 case UTT_IsIntegral:
4883 return T->isIntegralType(C);
4884 case UTT_IsFloatingPoint:
4885 return T->isFloatingType();
4886 case UTT_IsArray:
4887 return T->isArrayType();
4888 case UTT_IsPointer:
4889 return T->isAnyPointerType();
4890 case UTT_IsLvalueReference:
4891 return T->isLValueReferenceType();
4892 case UTT_IsRvalueReference:
4893 return T->isRValueReferenceType();
4894 case UTT_IsMemberFunctionPointer:
4895 return T->isMemberFunctionPointerType();
4896 case UTT_IsMemberObjectPointer:
4897 return T->isMemberDataPointerType();
4898 case UTT_IsEnum:
4899 return T->isEnumeralType();
4900 case UTT_IsUnion:
4901 return T->isUnionType();
4902 case UTT_IsClass:
4903 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4904 case UTT_IsFunction:
4905 return T->isFunctionType();
4906
4907 // Type trait expressions which correspond to the convenient composition
4908 // predicates in C++0x [meta.unary.comp].
4909 case UTT_IsReference:
4910 return T->isReferenceType();
4911 case UTT_IsArithmetic:
4912 return T->isArithmeticType() && !T->isEnumeralType();
4913 case UTT_IsFundamental:
4914 return T->isFundamentalType();
4915 case UTT_IsObject:
4916 return T->isObjectType();
4917 case UTT_IsScalar:
4918 // Note: semantic analysis depends on Objective-C lifetime types to be
4919 // considered scalar types. However, such types do not actually behave
4920 // like scalar types at run time (since they may require retain/release
4921 // operations), so we report them as non-scalar.
4922 if (T->isObjCLifetimeType()) {
4923 switch (T.getObjCLifetime()) {
4924 case Qualifiers::OCL_None:
4925 case Qualifiers::OCL_ExplicitNone:
4926 return true;
4927
4928 case Qualifiers::OCL_Strong:
4929 case Qualifiers::OCL_Weak:
4930 case Qualifiers::OCL_Autoreleasing:
4931 return false;
4932 }
4933 }
4934
4935 return T->isScalarType();
4936 case UTT_IsCompound:
4937 return T->isCompoundType();
4938 case UTT_IsMemberPointer:
4939 return T->isMemberPointerType();
4940
4941 // Type trait expressions which correspond to the type property predicates
4942 // in C++0x [meta.unary.prop].
4943 case UTT_IsConst:
4944 return T.isConstQualified();
4945 case UTT_IsVolatile:
4946 return T.isVolatileQualified();
4947 case UTT_IsTrivial:
4948 return T.isTrivialType(C);
4949 case UTT_IsTriviallyCopyable:
4950 return T.isTriviallyCopyableType(C);
4951 case UTT_IsStandardLayout:
4952 return T->isStandardLayoutType();
4953 case UTT_IsPOD:
4954 return T.isPODType(C);
4955 case UTT_IsLiteral:
4956 return T->isLiteralType(C);
4957 case UTT_IsEmpty:
4958 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4959 return !RD->isUnion() && RD->isEmpty();
4960 return false;
4961 case UTT_IsPolymorphic:
4962 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4963 return !RD->isUnion() && RD->isPolymorphic();
4964 return false;
4965 case UTT_IsAbstract:
4966 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4967 return !RD->isUnion() && RD->isAbstract();
4968 return false;
4969 case UTT_IsAggregate:
4970 // Report vector extensions and complex types as aggregates because they
4971 // support aggregate initialization. GCC mirrors this behavior for vectors
4972 // but not _Complex.
4973 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4974 T->isAnyComplexType();
4975 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4976 // even then only when it is used with the 'interface struct ...' syntax
4977 // Clang doesn't support /CLR which makes this type trait moot.
4978 case UTT_IsInterfaceClass:
4979 return false;
4980 case UTT_IsFinal:
4981 case UTT_IsSealed:
4982 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4983 return RD->hasAttr<FinalAttr>();
4984 return false;
4985 case UTT_IsSigned:
4986 // Enum types should always return false.
4987 // Floating points should always return true.
4988 return T->isFloatingType() ||
4989 (T->isSignedIntegerType() && !T->isEnumeralType());
4990 case UTT_IsUnsigned:
4991 // Enum types should always return false.
4992 return T->isUnsignedIntegerType() && !T->isEnumeralType();
4993
4994 // Type trait expressions which query classes regarding their construction,
4995 // destruction, and copying. Rather than being based directly on the
4996 // related type predicates in the standard, they are specified by both
4997 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4998 // specifications.
4999 //
5000 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
5001 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5002 //
5003 // Note that these builtins do not behave as documented in g++: if a class
5004 // has both a trivial and a non-trivial special member of a particular kind,
5005 // they return false! For now, we emulate this behavior.
5006 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
5007 // does not correctly compute triviality in the presence of multiple special
5008 // members of the same kind. Revisit this once the g++ bug is fixed.
5009 case UTT_HasTrivialDefaultConstructor:
5010 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5011 // If __is_pod (type) is true then the trait is true, else if type is
5012 // a cv class or union type (or array thereof) with a trivial default
5013 // constructor ([class.ctor]) then the trait is true, else it is false.
5014 if (T.isPODType(C))
5015 return true;
5016 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5017 return RD->hasTrivialDefaultConstructor() &&
5018 !RD->hasNonTrivialDefaultConstructor();
5019 return false;
5020 case UTT_HasTrivialMoveConstructor:
5021 // This trait is implemented by MSVC 2012 and needed to parse the
5022 // standard library headers. Specifically this is used as the logic
5023 // behind std::is_trivially_move_constructible (20.9.4.3).
5024 if (T.isPODType(C))
5025 return true;
5026 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5027 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
5028 return false;
5029 case UTT_HasTrivialCopy:
5030 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5031 // If __is_pod (type) is true or type is a reference type then
5032 // the trait is true, else if type is a cv class or union type
5033 // with a trivial copy constructor ([class.copy]) then the trait
5034 // is true, else it is false.
5035 if (T.isPODType(C) || T->isReferenceType())
5036 return true;
5037 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5038 return RD->hasTrivialCopyConstructor() &&
5039 !RD->hasNonTrivialCopyConstructor();
5040 return false;
5041 case UTT_HasTrivialMoveAssign:
5042 // This trait is implemented by MSVC 2012 and needed to parse the
5043 // standard library headers. Specifically it is used as the logic
5044 // behind std::is_trivially_move_assignable (20.9.4.3)
5045 if (T.isPODType(C))
5046 return true;
5047 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5048 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
5049 return false;
5050 case UTT_HasTrivialAssign:
5051 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5052 // If type is const qualified or is a reference type then the
5053 // trait is false. Otherwise if __is_pod (type) is true then the
5054 // trait is true, else if type is a cv class or union type with
5055 // a trivial copy assignment ([class.copy]) then the trait is
5056 // true, else it is false.
5057 // Note: the const and reference restrictions are interesting,
5058 // given that const and reference members don't prevent a class
5059 // from having a trivial copy assignment operator (but do cause
5060 // errors if the copy assignment operator is actually used, q.v.
5061 // [class.copy]p12).
5062
5063 if (T.isConstQualified())
5064 return false;
5065 if (T.isPODType(C))
5066 return true;
5067 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5068 return RD->hasTrivialCopyAssignment() &&
5069 !RD->hasNonTrivialCopyAssignment();
5070 return false;
5071 case UTT_IsDestructible:
5072 case UTT_IsTriviallyDestructible:
5073 case UTT_IsNothrowDestructible:
5074 // C++14 [meta.unary.prop]:
5075 // For reference types, is_destructible<T>::value is true.
5076 if (T->isReferenceType())
5077 return true;
5078
5079 // Objective-C++ ARC: autorelease types don't require destruction.
5080 if (T->isObjCLifetimeType() &&
5081 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5082 return true;
5083
5084 // C++14 [meta.unary.prop]:
5085 // For incomplete types and function types, is_destructible<T>::value is
5086 // false.
5087 if (T->isIncompleteType() || T->isFunctionType())
5088 return false;
5089
5090 // A type that requires destruction (via a non-trivial destructor or ARC
5091 // lifetime semantics) is not trivially-destructible.
5092 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
5093 return false;
5094
5095 // C++14 [meta.unary.prop]:
5096 // For object types and given U equal to remove_all_extents_t<T>, if the
5097 // expression std::declval<U&>().~U() is well-formed when treated as an
5098 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
5099 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5100 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5101 if (!Destructor)
5102 return false;
5103 // C++14 [dcl.fct.def.delete]p2:
5104 // A program that refers to a deleted function implicitly or
5105 // explicitly, other than to declare it, is ill-formed.
5106 if (Destructor->isDeleted())
5107 return false;
5108 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5109 return false;
5110 if (UTT == UTT_IsNothrowDestructible) {
5111 auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5112 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5113 if (!CPT || !CPT->isNothrow())
5114 return false;
5115 }
5116 }
5117 return true;
5118
5119 case UTT_HasTrivialDestructor:
5120 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5121 // If __is_pod (type) is true or type is a reference type
5122 // then the trait is true, else if type is a cv class or union
5123 // type (or array thereof) with a trivial destructor
5124 // ([class.dtor]) then the trait is true, else it is
5125 // false.
5126 if (T.isPODType(C) || T->isReferenceType())
5127 return true;
5128
5129 // Objective-C++ ARC: autorelease types don't require destruction.
5130 if (T->isObjCLifetimeType() &&
5131 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5132 return true;
5133
5134 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5135 return RD->hasTrivialDestructor();
5136 return false;
5137 // TODO: Propagate nothrowness for implicitly declared special members.
5138 case UTT_HasNothrowAssign:
5139 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5140 // If type is const qualified or is a reference type then the
5141 // trait is false. Otherwise if __has_trivial_assign (type)
5142 // is true then the trait is true, else if type is a cv class
5143 // or union type with copy assignment operators that are known
5144 // not to throw an exception then the trait is true, else it is
5145 // false.
5146 if (C.getBaseElementType(T).isConstQualified())
5147 return false;
5148 if (T->isReferenceType())
5149 return false;
5150 if (T.isPODType(C) || T->isObjCLifetimeType())
5151 return true;
5152
5153 if (const RecordType *RT = T->getAs<RecordType>())
5154 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5155 &CXXRecordDecl::hasTrivialCopyAssignment,
5156 &CXXRecordDecl::hasNonTrivialCopyAssignment,
5157 &CXXMethodDecl::isCopyAssignmentOperator);
5158 return false;
5159 case UTT_HasNothrowMoveAssign:
5160 // This trait is implemented by MSVC 2012 and needed to parse the
5161 // standard library headers. Specifically this is used as the logic
5162 // behind std::is_nothrow_move_assignable (20.9.4.3).
5163 if (T.isPODType(C))
5164 return true;
5165
5166 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5167 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5168 &CXXRecordDecl::hasTrivialMoveAssignment,
5169 &CXXRecordDecl::hasNonTrivialMoveAssignment,
5170 &CXXMethodDecl::isMoveAssignmentOperator);
5171 return false;
5172 case UTT_HasNothrowCopy:
5173 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5174 // If __has_trivial_copy (type) is true then the trait is true, else
5175 // if type is a cv class or union type with copy constructors that are
5176 // known not to throw an exception then the trait is true, else it is
5177 // false.
5178 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
5179 return true;
5180 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5181 if (RD->hasTrivialCopyConstructor() &&
5182 !RD->hasNonTrivialCopyConstructor())
5183 return true;
5184
5185 bool FoundConstructor = false;
5186 unsigned FoundTQs;
5187 for (const auto *ND : Self.LookupConstructors(RD)) {
5188 // A template constructor is never a copy constructor.
5189 // FIXME: However, it may actually be selected at the actual overload
5190 // resolution point.
5191 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5192 continue;
5193 // UsingDecl itself is not a constructor
5194 if (isa<UsingDecl>(ND))
5195 continue;
5196 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5197 if (Constructor->isCopyConstructor(FoundTQs)) {
5198 FoundConstructor = true;
5199 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5200 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5201 if (!CPT)
5202 return false;
5203 // TODO: check whether evaluating default arguments can throw.
5204 // For now, we'll be conservative and assume that they can throw.
5205 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5206 return false;
5207 }
5208 }
5209
5210 return FoundConstructor;
5211 }
5212 return false;
5213 case UTT_HasNothrowConstructor:
5214 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5215 // If __has_trivial_constructor (type) is true then the trait is
5216 // true, else if type is a cv class or union type (or array
5217 // thereof) with a default constructor that is known not to
5218 // throw an exception then the trait is true, else it is false.
5219 if (T.isPODType(C) || T->isObjCLifetimeType())
5220 return true;
5221 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5222 if (RD->hasTrivialDefaultConstructor() &&
5223 !RD->hasNonTrivialDefaultConstructor())
5224 return true;
5225
5226 bool FoundConstructor = false;
5227 for (const auto *ND : Self.LookupConstructors(RD)) {
5228 // FIXME: In C++0x, a constructor template can be a default constructor.
5229 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5230 continue;
5231 // UsingDecl itself is not a constructor
5232 if (isa<UsingDecl>(ND))
5233 continue;
5234 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5235 if (Constructor->isDefaultConstructor()) {
5236 FoundConstructor = true;
5237 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5238 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5239 if (!CPT)
5240 return false;
5241 // FIXME: check whether evaluating default arguments can throw.
5242 // For now, we'll be conservative and assume that they can throw.
5243 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5244 return false;
5245 }
5246 }
5247 return FoundConstructor;
5248 }
5249 return false;
5250 case UTT_HasVirtualDestructor:
5251 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5252 // If type is a class type with a virtual destructor ([class.dtor])
5253 // then the trait is true, else it is false.
5254 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5255 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5256 return Destructor->isVirtual();
5257 return false;
5258
5259 // These type trait expressions are modeled on the specifications for the
5260 // Embarcadero C++0x type trait functions:
5261 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5262 case UTT_IsCompleteType:
5263 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5264 // Returns True if and only if T is a complete type at the point of the
5265 // function call.
5266 return !T->isIncompleteType();
5267 case UTT_HasUniqueObjectRepresentations:
5268 return C.hasUniqueObjectRepresentations(T);
5269 case UTT_IsTriviallyRelocatable:
5270 return T.isTriviallyRelocatableType(C);
5271 }
5272 }
5273
5274 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5275 QualType RhsT, SourceLocation KeyLoc);
5276
evaluateTypeTrait(Sema & S,TypeTrait Kind,SourceLocation KWLoc,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc)5277 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
5278 ArrayRef<TypeSourceInfo *> Args,
5279 SourceLocation RParenLoc) {
5280 if (Kind <= UTT_Last)
5281 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
5282
5283 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
5284 // traits to avoid duplication.
5285 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
5286 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
5287 Args[1]->getType(), RParenLoc);
5288
5289 switch (Kind) {
5290 case clang::BTT_ReferenceBindsToTemporary:
5291 case clang::TT_IsConstructible:
5292 case clang::TT_IsNothrowConstructible:
5293 case clang::TT_IsTriviallyConstructible: {
5294 // C++11 [meta.unary.prop]:
5295 // is_trivially_constructible is defined as:
5296 //
5297 // is_constructible<T, Args...>::value is true and the variable
5298 // definition for is_constructible, as defined below, is known to call
5299 // no operation that is not trivial.
5300 //
5301 // The predicate condition for a template specialization
5302 // is_constructible<T, Args...> shall be satisfied if and only if the
5303 // following variable definition would be well-formed for some invented
5304 // variable t:
5305 //
5306 // T t(create<Args>()...);
5307 assert(!Args.empty());
5308
5309 // Precondition: T and all types in the parameter pack Args shall be
5310 // complete types, (possibly cv-qualified) void, or arrays of
5311 // unknown bound.
5312 for (const auto *TSI : Args) {
5313 QualType ArgTy = TSI->getType();
5314 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5315 continue;
5316
5317 if (S.RequireCompleteType(KWLoc, ArgTy,
5318 diag::err_incomplete_type_used_in_type_trait_expr))
5319 return false;
5320 }
5321
5322 // Make sure the first argument is not incomplete nor a function type.
5323 QualType T = Args[0]->getType();
5324 if (T->isIncompleteType() || T->isFunctionType())
5325 return false;
5326
5327 // Make sure the first argument is not an abstract type.
5328 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5329 if (RD && RD->isAbstract())
5330 return false;
5331
5332 llvm::BumpPtrAllocator OpaqueExprAllocator;
5333 SmallVector<Expr *, 2> ArgExprs;
5334 ArgExprs.reserve(Args.size() - 1);
5335 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5336 QualType ArgTy = Args[I]->getType();
5337 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5338 ArgTy = S.Context.getRValueReferenceType(ArgTy);
5339 ArgExprs.push_back(
5340 new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5341 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5342 ArgTy.getNonLValueExprType(S.Context),
5343 Expr::getValueKindForType(ArgTy)));
5344 }
5345
5346 // Perform the initialization in an unevaluated context within a SFINAE
5347 // trap at translation unit scope.
5348 EnterExpressionEvaluationContext Unevaluated(
5349 S, Sema::ExpressionEvaluationContext::Unevaluated);
5350 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5351 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
5352 InitializedEntity To(
5353 InitializedEntity::InitializeTemporary(S.Context, Args[0]));
5354 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
5355 RParenLoc));
5356 InitializationSequence Init(S, To, InitKind, ArgExprs);
5357 if (Init.Failed())
5358 return false;
5359
5360 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5361 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5362 return false;
5363
5364 if (Kind == clang::TT_IsConstructible)
5365 return true;
5366
5367 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
5368 if (!T->isReferenceType())
5369 return false;
5370
5371 return !Init.isDirectReferenceBinding();
5372 }
5373
5374 if (Kind == clang::TT_IsNothrowConstructible)
5375 return S.canThrow(Result.get()) == CT_Cannot;
5376
5377 if (Kind == clang::TT_IsTriviallyConstructible) {
5378 // Under Objective-C ARC and Weak, if the destination has non-trivial
5379 // Objective-C lifetime, this is a non-trivial construction.
5380 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5381 return false;
5382
5383 // The initialization succeeded; now make sure there are no non-trivial
5384 // calls.
5385 return !Result.get()->hasNonTrivialCall(S.Context);
5386 }
5387
5388 llvm_unreachable("unhandled type trait");
5389 return false;
5390 }
5391 default: llvm_unreachable("not a TT");
5392 }
5393
5394 return false;
5395 }
5396
5397 namespace {
DiagnoseBuiltinDeprecation(Sema & S,TypeTrait Kind,SourceLocation KWLoc)5398 void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind,
5399 SourceLocation KWLoc) {
5400 TypeTrait Replacement;
5401 switch (Kind) {
5402 case UTT_HasNothrowAssign:
5403 case UTT_HasNothrowMoveAssign:
5404 Replacement = BTT_IsNothrowAssignable;
5405 break;
5406 case UTT_HasNothrowCopy:
5407 case UTT_HasNothrowConstructor:
5408 Replacement = TT_IsNothrowConstructible;
5409 break;
5410 case UTT_HasTrivialAssign:
5411 case UTT_HasTrivialMoveAssign:
5412 Replacement = BTT_IsTriviallyAssignable;
5413 break;
5414 case UTT_HasTrivialCopy:
5415 Replacement = UTT_IsTriviallyCopyable;
5416 break;
5417 case UTT_HasTrivialDefaultConstructor:
5418 case UTT_HasTrivialMoveConstructor:
5419 Replacement = TT_IsTriviallyConstructible;
5420 break;
5421 case UTT_HasTrivialDestructor:
5422 Replacement = UTT_IsTriviallyDestructible;
5423 break;
5424 default:
5425 return;
5426 }
5427 S.Diag(KWLoc, diag::warn_deprecated_builtin)
5428 << getTraitSpelling(Kind) << getTraitSpelling(Replacement);
5429 }
5430 }
5431
BuildTypeTrait(TypeTrait Kind,SourceLocation KWLoc,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc)5432 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5433 ArrayRef<TypeSourceInfo *> Args,
5434 SourceLocation RParenLoc) {
5435 QualType ResultType = Context.getLogicalOperationType();
5436
5437 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5438 *this, Kind, KWLoc, Args[0]->getType()))
5439 return ExprError();
5440
5441 DiagnoseBuiltinDeprecation(*this, Kind, KWLoc);
5442
5443 bool Dependent = false;
5444 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5445 if (Args[I]->getType()->isDependentType()) {
5446 Dependent = true;
5447 break;
5448 }
5449 }
5450
5451 bool Result = false;
5452 if (!Dependent)
5453 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5454
5455 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5456 RParenLoc, Result);
5457 }
5458
ActOnTypeTrait(TypeTrait Kind,SourceLocation KWLoc,ArrayRef<ParsedType> Args,SourceLocation RParenLoc)5459 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5460 ArrayRef<ParsedType> Args,
5461 SourceLocation RParenLoc) {
5462 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5463 ConvertedArgs.reserve(Args.size());
5464
5465 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5466 TypeSourceInfo *TInfo;
5467 QualType T = GetTypeFromParser(Args[I], &TInfo);
5468 if (!TInfo)
5469 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5470
5471 ConvertedArgs.push_back(TInfo);
5472 }
5473
5474 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5475 }
5476
EvaluateBinaryTypeTrait(Sema & Self,TypeTrait BTT,QualType LhsT,QualType RhsT,SourceLocation KeyLoc)5477 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5478 QualType RhsT, SourceLocation KeyLoc) {
5479 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5480 "Cannot evaluate traits of dependent types");
5481
5482 switch(BTT) {
5483 case BTT_IsBaseOf: {
5484 // C++0x [meta.rel]p2
5485 // Base is a base class of Derived without regard to cv-qualifiers or
5486 // Base and Derived are not unions and name the same class type without
5487 // regard to cv-qualifiers.
5488
5489 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5490 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5491 if (!rhsRecord || !lhsRecord) {
5492 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5493 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5494 if (!LHSObjTy || !RHSObjTy)
5495 return false;
5496
5497 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5498 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5499 if (!BaseInterface || !DerivedInterface)
5500 return false;
5501
5502 if (Self.RequireCompleteType(
5503 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5504 return false;
5505
5506 return BaseInterface->isSuperClassOf(DerivedInterface);
5507 }
5508
5509 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5510 == (lhsRecord == rhsRecord));
5511
5512 // Unions are never base classes, and never have base classes.
5513 // It doesn't matter if they are complete or not. See PR#41843
5514 if (lhsRecord && lhsRecord->getDecl()->isUnion())
5515 return false;
5516 if (rhsRecord && rhsRecord->getDecl()->isUnion())
5517 return false;
5518
5519 if (lhsRecord == rhsRecord)
5520 return true;
5521
5522 // C++0x [meta.rel]p2:
5523 // If Base and Derived are class types and are different types
5524 // (ignoring possible cv-qualifiers) then Derived shall be a
5525 // complete type.
5526 if (Self.RequireCompleteType(KeyLoc, RhsT,
5527 diag::err_incomplete_type_used_in_type_trait_expr))
5528 return false;
5529
5530 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5531 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5532 }
5533 case BTT_IsSame:
5534 return Self.Context.hasSameType(LhsT, RhsT);
5535 case BTT_TypeCompatible: {
5536 // GCC ignores cv-qualifiers on arrays for this builtin.
5537 Qualifiers LhsQuals, RhsQuals;
5538 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5539 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5540 return Self.Context.typesAreCompatible(Lhs, Rhs);
5541 }
5542 case BTT_IsConvertible:
5543 case BTT_IsConvertibleTo: {
5544 // C++0x [meta.rel]p4:
5545 // Given the following function prototype:
5546 //
5547 // template <class T>
5548 // typename add_rvalue_reference<T>::type create();
5549 //
5550 // the predicate condition for a template specialization
5551 // is_convertible<From, To> shall be satisfied if and only if
5552 // the return expression in the following code would be
5553 // well-formed, including any implicit conversions to the return
5554 // type of the function:
5555 //
5556 // To test() {
5557 // return create<From>();
5558 // }
5559 //
5560 // Access checking is performed as if in a context unrelated to To and
5561 // From. Only the validity of the immediate context of the expression
5562 // of the return-statement (including conversions to the return type)
5563 // is considered.
5564 //
5565 // We model the initialization as a copy-initialization of a temporary
5566 // of the appropriate type, which for this expression is identical to the
5567 // return statement (since NRVO doesn't apply).
5568
5569 // Functions aren't allowed to return function or array types.
5570 if (RhsT->isFunctionType() || RhsT->isArrayType())
5571 return false;
5572
5573 // A return statement in a void function must have void type.
5574 if (RhsT->isVoidType())
5575 return LhsT->isVoidType();
5576
5577 // A function definition requires a complete, non-abstract return type.
5578 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5579 return false;
5580
5581 // Compute the result of add_rvalue_reference.
5582 if (LhsT->isObjectType() || LhsT->isFunctionType())
5583 LhsT = Self.Context.getRValueReferenceType(LhsT);
5584
5585 // Build a fake source and destination for initialization.
5586 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
5587 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5588 Expr::getValueKindForType(LhsT));
5589 Expr *FromPtr = &From;
5590 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
5591 SourceLocation()));
5592
5593 // Perform the initialization in an unevaluated context within a SFINAE
5594 // trap at translation unit scope.
5595 EnterExpressionEvaluationContext Unevaluated(
5596 Self, Sema::ExpressionEvaluationContext::Unevaluated);
5597 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5598 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5599 InitializationSequence Init(Self, To, Kind, FromPtr);
5600 if (Init.Failed())
5601 return false;
5602
5603 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5604 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5605 }
5606
5607 case BTT_IsAssignable:
5608 case BTT_IsNothrowAssignable:
5609 case BTT_IsTriviallyAssignable: {
5610 // C++11 [meta.unary.prop]p3:
5611 // is_trivially_assignable is defined as:
5612 // is_assignable<T, U>::value is true and the assignment, as defined by
5613 // is_assignable, is known to call no operation that is not trivial
5614 //
5615 // is_assignable is defined as:
5616 // The expression declval<T>() = declval<U>() is well-formed when
5617 // treated as an unevaluated operand (Clause 5).
5618 //
5619 // For both, T and U shall be complete types, (possibly cv-qualified)
5620 // void, or arrays of unknown bound.
5621 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5622 Self.RequireCompleteType(KeyLoc, LhsT,
5623 diag::err_incomplete_type_used_in_type_trait_expr))
5624 return false;
5625 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5626 Self.RequireCompleteType(KeyLoc, RhsT,
5627 diag::err_incomplete_type_used_in_type_trait_expr))
5628 return false;
5629
5630 // cv void is never assignable.
5631 if (LhsT->isVoidType() || RhsT->isVoidType())
5632 return false;
5633
5634 // Build expressions that emulate the effect of declval<T>() and
5635 // declval<U>().
5636 if (LhsT->isObjectType() || LhsT->isFunctionType())
5637 LhsT = Self.Context.getRValueReferenceType(LhsT);
5638 if (RhsT->isObjectType() || RhsT->isFunctionType())
5639 RhsT = Self.Context.getRValueReferenceType(RhsT);
5640 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5641 Expr::getValueKindForType(LhsT));
5642 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5643 Expr::getValueKindForType(RhsT));
5644
5645 // Attempt the assignment in an unevaluated context within a SFINAE
5646 // trap at translation unit scope.
5647 EnterExpressionEvaluationContext Unevaluated(
5648 Self, Sema::ExpressionEvaluationContext::Unevaluated);
5649 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5650 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5651 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5652 &Rhs);
5653 if (Result.isInvalid())
5654 return false;
5655
5656 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
5657 Self.CheckUnusedVolatileAssignment(Result.get());
5658
5659 if (SFINAE.hasErrorOccurred())
5660 return false;
5661
5662 if (BTT == BTT_IsAssignable)
5663 return true;
5664
5665 if (BTT == BTT_IsNothrowAssignable)
5666 return Self.canThrow(Result.get()) == CT_Cannot;
5667
5668 if (BTT == BTT_IsTriviallyAssignable) {
5669 // Under Objective-C ARC and Weak, if the destination has non-trivial
5670 // Objective-C lifetime, this is a non-trivial assignment.
5671 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5672 return false;
5673
5674 return !Result.get()->hasNonTrivialCall(Self.Context);
5675 }
5676
5677 llvm_unreachable("unhandled type trait");
5678 return false;
5679 }
5680 default: llvm_unreachable("not a BTT");
5681 }
5682 llvm_unreachable("Unknown type trait or not implemented");
5683 }
5684
ActOnArrayTypeTrait(ArrayTypeTrait ATT,SourceLocation KWLoc,ParsedType Ty,Expr * DimExpr,SourceLocation RParen)5685 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5686 SourceLocation KWLoc,
5687 ParsedType Ty,
5688 Expr* DimExpr,
5689 SourceLocation RParen) {
5690 TypeSourceInfo *TSInfo;
5691 QualType T = GetTypeFromParser(Ty, &TSInfo);
5692 if (!TSInfo)
5693 TSInfo = Context.getTrivialTypeSourceInfo(T);
5694
5695 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5696 }
5697
EvaluateArrayTypeTrait(Sema & Self,ArrayTypeTrait ATT,QualType T,Expr * DimExpr,SourceLocation KeyLoc)5698 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5699 QualType T, Expr *DimExpr,
5700 SourceLocation KeyLoc) {
5701 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5702
5703 switch(ATT) {
5704 case ATT_ArrayRank:
5705 if (T->isArrayType()) {
5706 unsigned Dim = 0;
5707 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5708 ++Dim;
5709 T = AT->getElementType();
5710 }
5711 return Dim;
5712 }
5713 return 0;
5714
5715 case ATT_ArrayExtent: {
5716 llvm::APSInt Value;
5717 uint64_t Dim;
5718 if (Self.VerifyIntegerConstantExpression(
5719 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
5720 .isInvalid())
5721 return 0;
5722 if (Value.isSigned() && Value.isNegative()) {
5723 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5724 << DimExpr->getSourceRange();
5725 return 0;
5726 }
5727 Dim = Value.getLimitedValue();
5728
5729 if (T->isArrayType()) {
5730 unsigned D = 0;
5731 bool Matched = false;
5732 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5733 if (Dim == D) {
5734 Matched = true;
5735 break;
5736 }
5737 ++D;
5738 T = AT->getElementType();
5739 }
5740
5741 if (Matched && T->isArrayType()) {
5742 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5743 return CAT->getSize().getLimitedValue();
5744 }
5745 }
5746 return 0;
5747 }
5748 }
5749 llvm_unreachable("Unknown type trait or not implemented");
5750 }
5751
BuildArrayTypeTrait(ArrayTypeTrait ATT,SourceLocation KWLoc,TypeSourceInfo * TSInfo,Expr * DimExpr,SourceLocation RParen)5752 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5753 SourceLocation KWLoc,
5754 TypeSourceInfo *TSInfo,
5755 Expr* DimExpr,
5756 SourceLocation RParen) {
5757 QualType T = TSInfo->getType();
5758
5759 // FIXME: This should likely be tracked as an APInt to remove any host
5760 // assumptions about the width of size_t on the target.
5761 uint64_t Value = 0;
5762 if (!T->isDependentType())
5763 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5764
5765 // While the specification for these traits from the Embarcadero C++
5766 // compiler's documentation says the return type is 'unsigned int', Clang
5767 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5768 // compiler, there is no difference. On several other platforms this is an
5769 // important distinction.
5770 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5771 RParen, Context.getSizeType());
5772 }
5773
ActOnExpressionTrait(ExpressionTrait ET,SourceLocation KWLoc,Expr * Queried,SourceLocation RParen)5774 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5775 SourceLocation KWLoc,
5776 Expr *Queried,
5777 SourceLocation RParen) {
5778 // If error parsing the expression, ignore.
5779 if (!Queried)
5780 return ExprError();
5781
5782 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5783
5784 return Result;
5785 }
5786
EvaluateExpressionTrait(ExpressionTrait ET,Expr * E)5787 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5788 switch (ET) {
5789 case ET_IsLValueExpr: return E->isLValue();
5790 case ET_IsRValueExpr:
5791 return E->isPRValue();
5792 }
5793 llvm_unreachable("Expression trait not covered by switch");
5794 }
5795
BuildExpressionTrait(ExpressionTrait ET,SourceLocation KWLoc,Expr * Queried,SourceLocation RParen)5796 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5797 SourceLocation KWLoc,
5798 Expr *Queried,
5799 SourceLocation RParen) {
5800 if (Queried->isTypeDependent()) {
5801 // Delay type-checking for type-dependent expressions.
5802 } else if (Queried->hasPlaceholderType()) {
5803 ExprResult PE = CheckPlaceholderExpr(Queried);
5804 if (PE.isInvalid()) return ExprError();
5805 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5806 }
5807
5808 bool Value = EvaluateExpressionTrait(ET, Queried);
5809
5810 return new (Context)
5811 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5812 }
5813
CheckPointerToMemberOperands(ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,SourceLocation Loc,bool isIndirect)5814 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5815 ExprValueKind &VK,
5816 SourceLocation Loc,
5817 bool isIndirect) {
5818 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
5819 "placeholders should have been weeded out by now");
5820
5821 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5822 // temporary materialization conversion otherwise.
5823 if (isIndirect)
5824 LHS = DefaultLvalueConversion(LHS.get());
5825 else if (LHS.get()->isPRValue())
5826 LHS = TemporaryMaterializationConversion(LHS.get());
5827 if (LHS.isInvalid())
5828 return QualType();
5829
5830 // The RHS always undergoes lvalue conversions.
5831 RHS = DefaultLvalueConversion(RHS.get());
5832 if (RHS.isInvalid()) return QualType();
5833
5834 const char *OpSpelling = isIndirect ? "->*" : ".*";
5835 // C++ 5.5p2
5836 // The binary operator .* [p3: ->*] binds its second operand, which shall
5837 // be of type "pointer to member of T" (where T is a completely-defined
5838 // class type) [...]
5839 QualType RHSType = RHS.get()->getType();
5840 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5841 if (!MemPtr) {
5842 Diag(Loc, diag::err_bad_memptr_rhs)
5843 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5844 return QualType();
5845 }
5846
5847 QualType Class(MemPtr->getClass(), 0);
5848
5849 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5850 // member pointer points must be completely-defined. However, there is no
5851 // reason for this semantic distinction, and the rule is not enforced by
5852 // other compilers. Therefore, we do not check this property, as it is
5853 // likely to be considered a defect.
5854
5855 // C++ 5.5p2
5856 // [...] to its first operand, which shall be of class T or of a class of
5857 // which T is an unambiguous and accessible base class. [p3: a pointer to
5858 // such a class]
5859 QualType LHSType = LHS.get()->getType();
5860 if (isIndirect) {
5861 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5862 LHSType = Ptr->getPointeeType();
5863 else {
5864 Diag(Loc, diag::err_bad_memptr_lhs)
5865 << OpSpelling << 1 << LHSType
5866 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5867 return QualType();
5868 }
5869 }
5870
5871 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5872 // If we want to check the hierarchy, we need a complete type.
5873 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5874 OpSpelling, (int)isIndirect)) {
5875 return QualType();
5876 }
5877
5878 if (!IsDerivedFrom(Loc, LHSType, Class)) {
5879 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5880 << (int)isIndirect << LHS.get()->getType();
5881 return QualType();
5882 }
5883
5884 CXXCastPath BasePath;
5885 if (CheckDerivedToBaseConversion(
5886 LHSType, Class, Loc,
5887 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5888 &BasePath))
5889 return QualType();
5890
5891 // Cast LHS to type of use.
5892 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5893 if (isIndirect)
5894 UseType = Context.getPointerType(UseType);
5895 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
5896 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5897 &BasePath);
5898 }
5899
5900 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5901 // Diagnose use of pointer-to-member type which when used as
5902 // the functional cast in a pointer-to-member expression.
5903 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5904 return QualType();
5905 }
5906
5907 // C++ 5.5p2
5908 // The result is an object or a function of the type specified by the
5909 // second operand.
5910 // The cv qualifiers are the union of those in the pointer and the left side,
5911 // in accordance with 5.5p5 and 5.2.5.
5912 QualType Result = MemPtr->getPointeeType();
5913 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5914
5915 // C++0x [expr.mptr.oper]p6:
5916 // In a .* expression whose object expression is an rvalue, the program is
5917 // ill-formed if the second operand is a pointer to member function with
5918 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5919 // expression is an lvalue, the program is ill-formed if the second operand
5920 // is a pointer to member function with ref-qualifier &&.
5921 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5922 switch (Proto->getRefQualifier()) {
5923 case RQ_None:
5924 // Do nothing
5925 break;
5926
5927 case RQ_LValue:
5928 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5929 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5930 // is (exactly) 'const'.
5931 if (Proto->isConst() && !Proto->isVolatile())
5932 Diag(Loc, getLangOpts().CPlusPlus20
5933 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5934 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5935 else
5936 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5937 << RHSType << 1 << LHS.get()->getSourceRange();
5938 }
5939 break;
5940
5941 case RQ_RValue:
5942 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5943 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5944 << RHSType << 0 << LHS.get()->getSourceRange();
5945 break;
5946 }
5947 }
5948
5949 // C++ [expr.mptr.oper]p6:
5950 // The result of a .* expression whose second operand is a pointer
5951 // to a data member is of the same value category as its
5952 // first operand. The result of a .* expression whose second
5953 // operand is a pointer to a member function is a prvalue. The
5954 // result of an ->* expression is an lvalue if its second operand
5955 // is a pointer to data member and a prvalue otherwise.
5956 if (Result->isFunctionType()) {
5957 VK = VK_PRValue;
5958 return Context.BoundMemberTy;
5959 } else if (isIndirect) {
5960 VK = VK_LValue;
5961 } else {
5962 VK = LHS.get()->getValueKind();
5963 }
5964
5965 return Result;
5966 }
5967
5968 /// Try to convert a type to another according to C++11 5.16p3.
5969 ///
5970 /// This is part of the parameter validation for the ? operator. If either
5971 /// value operand is a class type, the two operands are attempted to be
5972 /// converted to each other. This function does the conversion in one direction.
5973 /// It returns true if the program is ill-formed and has already been diagnosed
5974 /// as such.
TryClassUnification(Sema & Self,Expr * From,Expr * To,SourceLocation QuestionLoc,bool & HaveConversion,QualType & ToType)5975 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5976 SourceLocation QuestionLoc,
5977 bool &HaveConversion,
5978 QualType &ToType) {
5979 HaveConversion = false;
5980 ToType = To->getType();
5981
5982 InitializationKind Kind =
5983 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
5984 // C++11 5.16p3
5985 // The process for determining whether an operand expression E1 of type T1
5986 // can be converted to match an operand expression E2 of type T2 is defined
5987 // as follows:
5988 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5989 // implicitly converted to type "lvalue reference to T2", subject to the
5990 // constraint that in the conversion the reference must bind directly to
5991 // an lvalue.
5992 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5993 // implicitly converted to the type "rvalue reference to R2", subject to
5994 // the constraint that the reference must bind directly.
5995 if (To->isGLValue()) {
5996 QualType T = Self.Context.getReferenceQualifiedType(To);
5997 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5998
5999 InitializationSequence InitSeq(Self, Entity, Kind, From);
6000 if (InitSeq.isDirectReferenceBinding()) {
6001 ToType = T;
6002 HaveConversion = true;
6003 return false;
6004 }
6005
6006 if (InitSeq.isAmbiguous())
6007 return InitSeq.Diagnose(Self, Entity, Kind, From);
6008 }
6009
6010 // -- If E2 is an rvalue, or if the conversion above cannot be done:
6011 // -- if E1 and E2 have class type, and the underlying class types are
6012 // the same or one is a base class of the other:
6013 QualType FTy = From->getType();
6014 QualType TTy = To->getType();
6015 const RecordType *FRec = FTy->getAs<RecordType>();
6016 const RecordType *TRec = TTy->getAs<RecordType>();
6017 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
6018 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
6019 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
6020 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
6021 // E1 can be converted to match E2 if the class of T2 is the
6022 // same type as, or a base class of, the class of T1, and
6023 // [cv2 > cv1].
6024 if (FRec == TRec || FDerivedFromT) {
6025 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
6026 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
6027 InitializationSequence InitSeq(Self, Entity, Kind, From);
6028 if (InitSeq) {
6029 HaveConversion = true;
6030 return false;
6031 }
6032
6033 if (InitSeq.isAmbiguous())
6034 return InitSeq.Diagnose(Self, Entity, Kind, From);
6035 }
6036 }
6037
6038 return false;
6039 }
6040
6041 // -- Otherwise: E1 can be converted to match E2 if E1 can be
6042 // implicitly converted to the type that expression E2 would have
6043 // if E2 were converted to an rvalue (or the type it has, if E2 is
6044 // an rvalue).
6045 //
6046 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
6047 // to the array-to-pointer or function-to-pointer conversions.
6048 TTy = TTy.getNonLValueExprType(Self.Context);
6049
6050 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
6051 InitializationSequence InitSeq(Self, Entity, Kind, From);
6052 HaveConversion = !InitSeq.Failed();
6053 ToType = TTy;
6054 if (InitSeq.isAmbiguous())
6055 return InitSeq.Diagnose(Self, Entity, Kind, From);
6056
6057 return false;
6058 }
6059
6060 /// Try to find a common type for two according to C++0x 5.16p5.
6061 ///
6062 /// This is part of the parameter validation for the ? operator. If either
6063 /// value operand is a class type, overload resolution is used to find a
6064 /// conversion to a common type.
FindConditionalOverload(Sema & Self,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6065 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
6066 SourceLocation QuestionLoc) {
6067 Expr *Args[2] = { LHS.get(), RHS.get() };
6068 OverloadCandidateSet CandidateSet(QuestionLoc,
6069 OverloadCandidateSet::CSK_Operator);
6070 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
6071 CandidateSet);
6072
6073 OverloadCandidateSet::iterator Best;
6074 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
6075 case OR_Success: {
6076 // We found a match. Perform the conversions on the arguments and move on.
6077 ExprResult LHSRes = Self.PerformImplicitConversion(
6078 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
6079 Sema::AA_Converting);
6080 if (LHSRes.isInvalid())
6081 break;
6082 LHS = LHSRes;
6083
6084 ExprResult RHSRes = Self.PerformImplicitConversion(
6085 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
6086 Sema::AA_Converting);
6087 if (RHSRes.isInvalid())
6088 break;
6089 RHS = RHSRes;
6090 if (Best->Function)
6091 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
6092 return false;
6093 }
6094
6095 case OR_No_Viable_Function:
6096
6097 // Emit a better diagnostic if one of the expressions is a null pointer
6098 // constant and the other is a pointer type. In this case, the user most
6099 // likely forgot to take the address of the other expression.
6100 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6101 return true;
6102
6103 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6104 << LHS.get()->getType() << RHS.get()->getType()
6105 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6106 return true;
6107
6108 case OR_Ambiguous:
6109 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
6110 << LHS.get()->getType() << RHS.get()->getType()
6111 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6112 // FIXME: Print the possible common types by printing the return types of
6113 // the viable candidates.
6114 break;
6115
6116 case OR_Deleted:
6117 llvm_unreachable("Conditional operator has only built-in overloads");
6118 }
6119 return true;
6120 }
6121
6122 /// Perform an "extended" implicit conversion as returned by
6123 /// TryClassUnification.
ConvertForConditional(Sema & Self,ExprResult & E,QualType T)6124 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
6125 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
6126 InitializationKind Kind =
6127 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
6128 Expr *Arg = E.get();
6129 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
6130 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
6131 if (Result.isInvalid())
6132 return true;
6133
6134 E = Result;
6135 return false;
6136 }
6137
6138 // Check the condition operand of ?: to see if it is valid for the GCC
6139 // extension.
isValidVectorForConditionalCondition(ASTContext & Ctx,QualType CondTy)6140 static bool isValidVectorForConditionalCondition(ASTContext &Ctx,
6141 QualType CondTy) {
6142 if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
6143 return false;
6144 const QualType EltTy =
6145 cast<VectorType>(CondTy.getCanonicalType())->getElementType();
6146 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6147 return EltTy->isIntegralType(Ctx);
6148 }
6149
isValidSizelessVectorForConditionalCondition(ASTContext & Ctx,QualType CondTy)6150 static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx,
6151 QualType CondTy) {
6152 if (!CondTy->isVLSTBuiltinType())
6153 return false;
6154 const QualType EltTy =
6155 cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);
6156 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6157 return EltTy->isIntegralType(Ctx);
6158 }
6159
CheckVectorConditionalTypes(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6160 QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
6161 ExprResult &RHS,
6162 SourceLocation QuestionLoc) {
6163 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6164 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6165
6166 QualType CondType = Cond.get()->getType();
6167 const auto *CondVT = CondType->castAs<VectorType>();
6168 QualType CondElementTy = CondVT->getElementType();
6169 unsigned CondElementCount = CondVT->getNumElements();
6170 QualType LHSType = LHS.get()->getType();
6171 const auto *LHSVT = LHSType->getAs<VectorType>();
6172 QualType RHSType = RHS.get()->getType();
6173 const auto *RHSVT = RHSType->getAs<VectorType>();
6174
6175 QualType ResultType;
6176
6177
6178 if (LHSVT && RHSVT) {
6179 if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
6180 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
6181 << /*isExtVector*/ isa<ExtVectorType>(CondVT);
6182 return {};
6183 }
6184
6185 // If both are vector types, they must be the same type.
6186 if (!Context.hasSameType(LHSType, RHSType)) {
6187 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6188 << LHSType << RHSType;
6189 return {};
6190 }
6191 ResultType = LHSType;
6192 } else if (LHSVT || RHSVT) {
6193 ResultType = CheckVectorOperands(
6194 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6195 /*AllowBoolConversions*/ false,
6196 /*AllowBoolOperation*/ true,
6197 /*ReportInvalid*/ true);
6198 if (ResultType.isNull())
6199 return {};
6200 } else {
6201 // Both are scalar.
6202 QualType ResultElementTy;
6203 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6204 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6205
6206 if (Context.hasSameType(LHSType, RHSType))
6207 ResultElementTy = LHSType;
6208 else
6209 ResultElementTy =
6210 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6211
6212 if (ResultElementTy->isEnumeralType()) {
6213 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6214 << ResultElementTy;
6215 return {};
6216 }
6217 if (CondType->isExtVectorType())
6218 ResultType =
6219 Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
6220 else
6221 ResultType = Context.getVectorType(
6222 ResultElementTy, CondVT->getNumElements(), VectorType::GenericVector);
6223
6224 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6225 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6226 }
6227
6228 assert(!ResultType.isNull() && ResultType->isVectorType() &&
6229 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
6230 "Result should have been a vector type");
6231 auto *ResultVectorTy = ResultType->castAs<VectorType>();
6232 QualType ResultElementTy = ResultVectorTy->getElementType();
6233 unsigned ResultElementCount = ResultVectorTy->getNumElements();
6234
6235 if (ResultElementCount != CondElementCount) {
6236 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
6237 << ResultType;
6238 return {};
6239 }
6240
6241 if (Context.getTypeSize(ResultElementTy) !=
6242 Context.getTypeSize(CondElementTy)) {
6243 Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6244 << ResultType;
6245 return {};
6246 }
6247
6248 return ResultType;
6249 }
6250
CheckSizelessVectorConditionalTypes(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6251 QualType Sema::CheckSizelessVectorConditionalTypes(ExprResult &Cond,
6252 ExprResult &LHS,
6253 ExprResult &RHS,
6254 SourceLocation QuestionLoc) {
6255 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6256 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6257
6258 QualType CondType = Cond.get()->getType();
6259 const auto *CondBT = CondType->castAs<BuiltinType>();
6260 QualType CondElementTy = CondBT->getSveEltType(Context);
6261 llvm::ElementCount CondElementCount =
6262 Context.getBuiltinVectorTypeInfo(CondBT).EC;
6263
6264 QualType LHSType = LHS.get()->getType();
6265 const auto *LHSBT =
6266 LHSType->isVLSTBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;
6267 QualType RHSType = RHS.get()->getType();
6268 const auto *RHSBT =
6269 RHSType->isVLSTBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;
6270
6271 QualType ResultType;
6272
6273 if (LHSBT && RHSBT) {
6274 // If both are sizeless vector types, they must be the same type.
6275 if (!Context.hasSameType(LHSType, RHSType)) {
6276 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6277 << LHSType << RHSType;
6278 return QualType();
6279 }
6280 ResultType = LHSType;
6281 } else if (LHSBT || RHSBT) {
6282 ResultType = CheckSizelessVectorOperands(
6283 LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional);
6284 if (ResultType.isNull())
6285 return QualType();
6286 } else {
6287 // Both are scalar so splat
6288 QualType ResultElementTy;
6289 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6290 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6291
6292 if (Context.hasSameType(LHSType, RHSType))
6293 ResultElementTy = LHSType;
6294 else
6295 ResultElementTy =
6296 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6297
6298 if (ResultElementTy->isEnumeralType()) {
6299 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6300 << ResultElementTy;
6301 return QualType();
6302 }
6303
6304 ResultType = Context.getScalableVectorType(
6305 ResultElementTy, CondElementCount.getKnownMinValue());
6306
6307 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6308 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6309 }
6310
6311 assert(!ResultType.isNull() && ResultType->isVLSTBuiltinType() &&
6312 "Result should have been a vector type");
6313 auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();
6314 QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);
6315 llvm::ElementCount ResultElementCount =
6316 Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;
6317
6318 if (ResultElementCount != CondElementCount) {
6319 Diag(QuestionLoc, diag::err_conditional_vector_size)
6320 << CondType << ResultType;
6321 return QualType();
6322 }
6323
6324 if (Context.getTypeSize(ResultElementTy) !=
6325 Context.getTypeSize(CondElementTy)) {
6326 Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6327 << CondType << ResultType;
6328 return QualType();
6329 }
6330
6331 return ResultType;
6332 }
6333
6334 /// Check the operands of ?: under C++ semantics.
6335 ///
6336 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
6337 /// extension. In this case, LHS == Cond. (But they're not aliases.)
6338 ///
6339 /// This function also implements GCC's vector extension and the
6340 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
6341 /// permit the use of a?b:c where the type of a is that of a integer vector with
6342 /// the same number of elements and size as the vectors of b and c. If one of
6343 /// either b or c is a scalar it is implicitly converted to match the type of
6344 /// the vector. Otherwise the expression is ill-formed. If both b and c are
6345 /// scalars, then b and c are checked and converted to the type of a if
6346 /// possible.
6347 ///
6348 /// The expressions are evaluated differently for GCC's and OpenCL's extensions.
6349 /// For the GCC extension, the ?: operator is evaluated as
6350 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
6351 /// For the OpenCL extensions, the ?: operator is evaluated as
6352 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
6353 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
CXXCheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)6354 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6355 ExprResult &RHS, ExprValueKind &VK,
6356 ExprObjectKind &OK,
6357 SourceLocation QuestionLoc) {
6358 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6359 // pointers.
6360
6361 // Assume r-value.
6362 VK = VK_PRValue;
6363 OK = OK_Ordinary;
6364 bool IsVectorConditional =
6365 isValidVectorForConditionalCondition(Context, Cond.get()->getType());
6366
6367 bool IsSizelessVectorConditional =
6368 isValidSizelessVectorForConditionalCondition(Context,
6369 Cond.get()->getType());
6370
6371 // C++11 [expr.cond]p1
6372 // The first expression is contextually converted to bool.
6373 if (!Cond.get()->isTypeDependent()) {
6374 ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional
6375 ? DefaultFunctionArrayLvalueConversion(Cond.get())
6376 : CheckCXXBooleanCondition(Cond.get());
6377 if (CondRes.isInvalid())
6378 return QualType();
6379 Cond = CondRes;
6380 } else {
6381 // To implement C++, the first expression typically doesn't alter the result
6382 // type of the conditional, however the GCC compatible vector extension
6383 // changes the result type to be that of the conditional. Since we cannot
6384 // know if this is a vector extension here, delay the conversion of the
6385 // LHS/RHS below until later.
6386 return Context.DependentTy;
6387 }
6388
6389
6390 // Either of the arguments dependent?
6391 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
6392 return Context.DependentTy;
6393
6394 // C++11 [expr.cond]p2
6395 // If either the second or the third operand has type (cv) void, ...
6396 QualType LTy = LHS.get()->getType();
6397 QualType RTy = RHS.get()->getType();
6398 bool LVoid = LTy->isVoidType();
6399 bool RVoid = RTy->isVoidType();
6400 if (LVoid || RVoid) {
6401 // ... one of the following shall hold:
6402 // -- The second or the third operand (but not both) is a (possibly
6403 // parenthesized) throw-expression; the result is of the type
6404 // and value category of the other.
6405 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6406 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
6407
6408 // Void expressions aren't legal in the vector-conditional expressions.
6409 if (IsVectorConditional) {
6410 SourceRange DiagLoc =
6411 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6412 bool IsThrow = LVoid ? LThrow : RThrow;
6413 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6414 << DiagLoc << IsThrow;
6415 return QualType();
6416 }
6417
6418 if (LThrow != RThrow) {
6419 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6420 VK = NonThrow->getValueKind();
6421 // DR (no number yet): the result is a bit-field if the
6422 // non-throw-expression operand is a bit-field.
6423 OK = NonThrow->getObjectKind();
6424 return NonThrow->getType();
6425 }
6426
6427 // -- Both the second and third operands have type void; the result is of
6428 // type void and is a prvalue.
6429 if (LVoid && RVoid)
6430 return Context.VoidTy;
6431
6432 // Neither holds, error.
6433 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6434 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
6435 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6436 return QualType();
6437 }
6438
6439 // Neither is void.
6440 if (IsVectorConditional)
6441 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6442
6443 if (IsSizelessVectorConditional)
6444 return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6445
6446 // C++11 [expr.cond]p3
6447 // Otherwise, if the second and third operand have different types, and
6448 // either has (cv) class type [...] an attempt is made to convert each of
6449 // those operands to the type of the other.
6450 if (!Context.hasSameType(LTy, RTy) &&
6451 (LTy->isRecordType() || RTy->isRecordType())) {
6452 // These return true if a single direction is already ambiguous.
6453 QualType L2RType, R2LType;
6454 bool HaveL2R, HaveR2L;
6455 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
6456 return QualType();
6457 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
6458 return QualType();
6459
6460 // If both can be converted, [...] the program is ill-formed.
6461 if (HaveL2R && HaveR2L) {
6462 Diag(QuestionLoc, diag::err_conditional_ambiguous)
6463 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6464 return QualType();
6465 }
6466
6467 // If exactly one conversion is possible, that conversion is applied to
6468 // the chosen operand and the converted operands are used in place of the
6469 // original operands for the remainder of this section.
6470 if (HaveL2R) {
6471 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
6472 return QualType();
6473 LTy = LHS.get()->getType();
6474 } else if (HaveR2L) {
6475 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
6476 return QualType();
6477 RTy = RHS.get()->getType();
6478 }
6479 }
6480
6481 // C++11 [expr.cond]p3
6482 // if both are glvalues of the same value category and the same type except
6483 // for cv-qualification, an attempt is made to convert each of those
6484 // operands to the type of the other.
6485 // FIXME:
6486 // Resolving a defect in P0012R1: we extend this to cover all cases where
6487 // one of the operands is reference-compatible with the other, in order
6488 // to support conditionals between functions differing in noexcept. This
6489 // will similarly cover difference in array bounds after P0388R4.
6490 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6491 // that instead?
6492 ExprValueKind LVK = LHS.get()->getValueKind();
6493 ExprValueKind RVK = RHS.get()->getValueKind();
6494 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
6495 // DerivedToBase was already handled by the class-specific case above.
6496 // FIXME: Should we allow ObjC conversions here?
6497 const ReferenceConversions AllowedConversions =
6498 ReferenceConversions::Qualification |
6499 ReferenceConversions::NestedQualification |
6500 ReferenceConversions::Function;
6501
6502 ReferenceConversions RefConv;
6503 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6504 Ref_Compatible &&
6505 !(RefConv & ~AllowedConversions) &&
6506 // [...] subject to the constraint that the reference must bind
6507 // directly [...]
6508 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6509 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6510 RTy = RHS.get()->getType();
6511 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6512 Ref_Compatible &&
6513 !(RefConv & ~AllowedConversions) &&
6514 !LHS.get()->refersToBitField() &&
6515 !LHS.get()->refersToVectorElement()) {
6516 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6517 LTy = LHS.get()->getType();
6518 }
6519 }
6520
6521 // C++11 [expr.cond]p4
6522 // If the second and third operands are glvalues of the same value
6523 // category and have the same type, the result is of that type and
6524 // value category and it is a bit-field if the second or the third
6525 // operand is a bit-field, or if both are bit-fields.
6526 // We only extend this to bitfields, not to the crazy other kinds of
6527 // l-values.
6528 bool Same = Context.hasSameType(LTy, RTy);
6529 if (Same && LVK == RVK && LVK != VK_PRValue &&
6530 LHS.get()->isOrdinaryOrBitFieldObject() &&
6531 RHS.get()->isOrdinaryOrBitFieldObject()) {
6532 VK = LHS.get()->getValueKind();
6533 if (LHS.get()->getObjectKind() == OK_BitField ||
6534 RHS.get()->getObjectKind() == OK_BitField)
6535 OK = OK_BitField;
6536
6537 // If we have function pointer types, unify them anyway to unify their
6538 // exception specifications, if any.
6539 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6540 Qualifiers Qs = LTy.getQualifiers();
6541 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
6542 /*ConvertArgs*/false);
6543 LTy = Context.getQualifiedType(LTy, Qs);
6544
6545 assert(!LTy.isNull() && "failed to find composite pointer type for "
6546 "canonically equivalent function ptr types");
6547 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
6548 }
6549
6550 return LTy;
6551 }
6552
6553 // C++11 [expr.cond]p5
6554 // Otherwise, the result is a prvalue. If the second and third operands
6555 // do not have the same type, and either has (cv) class type, ...
6556 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6557 // ... overload resolution is used to determine the conversions (if any)
6558 // to be applied to the operands. If the overload resolution fails, the
6559 // program is ill-formed.
6560 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6561 return QualType();
6562 }
6563
6564 // C++11 [expr.cond]p6
6565 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6566 // conversions are performed on the second and third operands.
6567 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6568 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6569 if (LHS.isInvalid() || RHS.isInvalid())
6570 return QualType();
6571 LTy = LHS.get()->getType();
6572 RTy = RHS.get()->getType();
6573
6574 // After those conversions, one of the following shall hold:
6575 // -- The second and third operands have the same type; the result
6576 // is of that type. If the operands have class type, the result
6577 // is a prvalue temporary of the result type, which is
6578 // copy-initialized from either the second operand or the third
6579 // operand depending on the value of the first operand.
6580 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
6581 if (LTy->isRecordType()) {
6582 // The operands have class type. Make a temporary copy.
6583 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
6584
6585 ExprResult LHSCopy = PerformCopyInitialization(Entity,
6586 SourceLocation(),
6587 LHS);
6588 if (LHSCopy.isInvalid())
6589 return QualType();
6590
6591 ExprResult RHSCopy = PerformCopyInitialization(Entity,
6592 SourceLocation(),
6593 RHS);
6594 if (RHSCopy.isInvalid())
6595 return QualType();
6596
6597 LHS = LHSCopy;
6598 RHS = RHSCopy;
6599 }
6600
6601 // If we have function pointer types, unify them anyway to unify their
6602 // exception specifications, if any.
6603 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6604 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
6605 assert(!LTy.isNull() && "failed to find composite pointer type for "
6606 "canonically equivalent function ptr types");
6607 }
6608
6609 return LTy;
6610 }
6611
6612 // Extension: conditional operator involving vector types.
6613 if (LTy->isVectorType() || RTy->isVectorType())
6614 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
6615 /*AllowBothBool*/ true,
6616 /*AllowBoolConversions*/ false,
6617 /*AllowBoolOperation*/ false,
6618 /*ReportInvalid*/ true);
6619
6620 // -- The second and third operands have arithmetic or enumeration type;
6621 // the usual arithmetic conversions are performed to bring them to a
6622 // common type, and the result is of that type.
6623 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
6624 QualType ResTy =
6625 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6626 if (LHS.isInvalid() || RHS.isInvalid())
6627 return QualType();
6628 if (ResTy.isNull()) {
6629 Diag(QuestionLoc,
6630 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6631 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6632 return QualType();
6633 }
6634
6635 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6636 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6637
6638 return ResTy;
6639 }
6640
6641 // -- The second and third operands have pointer type, or one has pointer
6642 // type and the other is a null pointer constant, or both are null
6643 // pointer constants, at least one of which is non-integral; pointer
6644 // conversions and qualification conversions are performed to bring them
6645 // to their composite pointer type. The result is of the composite
6646 // pointer type.
6647 // -- The second and third operands have pointer to member type, or one has
6648 // pointer to member type and the other is a null pointer constant;
6649 // pointer to member conversions and qualification conversions are
6650 // performed to bring them to a common type, whose cv-qualification
6651 // shall match the cv-qualification of either the second or the third
6652 // operand. The result is of the common type.
6653 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6654 if (!Composite.isNull())
6655 return Composite;
6656
6657 // Similarly, attempt to find composite type of two objective-c pointers.
6658 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6659 if (LHS.isInvalid() || RHS.isInvalid())
6660 return QualType();
6661 if (!Composite.isNull())
6662 return Composite;
6663
6664 // Check if we are using a null with a non-pointer type.
6665 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6666 return QualType();
6667
6668 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6669 << LHS.get()->getType() << RHS.get()->getType()
6670 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6671 return QualType();
6672 }
6673
6674 static FunctionProtoType::ExceptionSpecInfo
mergeExceptionSpecs(Sema & S,FunctionProtoType::ExceptionSpecInfo ESI1,FunctionProtoType::ExceptionSpecInfo ESI2,SmallVectorImpl<QualType> & ExceptionTypeStorage)6675 mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
6676 FunctionProtoType::ExceptionSpecInfo ESI2,
6677 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6678 ExceptionSpecificationType EST1 = ESI1.Type;
6679 ExceptionSpecificationType EST2 = ESI2.Type;
6680
6681 // If either of them can throw anything, that is the result.
6682 if (EST1 == EST_None) return ESI1;
6683 if (EST2 == EST_None) return ESI2;
6684 if (EST1 == EST_MSAny) return ESI1;
6685 if (EST2 == EST_MSAny) return ESI2;
6686 if (EST1 == EST_NoexceptFalse) return ESI1;
6687 if (EST2 == EST_NoexceptFalse) return ESI2;
6688
6689 // If either of them is non-throwing, the result is the other.
6690 if (EST1 == EST_NoThrow) return ESI2;
6691 if (EST2 == EST_NoThrow) return ESI1;
6692 if (EST1 == EST_DynamicNone) return ESI2;
6693 if (EST2 == EST_DynamicNone) return ESI1;
6694 if (EST1 == EST_BasicNoexcept) return ESI2;
6695 if (EST2 == EST_BasicNoexcept) return ESI1;
6696 if (EST1 == EST_NoexceptTrue) return ESI2;
6697 if (EST2 == EST_NoexceptTrue) return ESI1;
6698
6699 // If we're left with value-dependent computed noexcept expressions, we're
6700 // stuck. Before C++17, we can just drop the exception specification entirely,
6701 // since it's not actually part of the canonical type. And this should never
6702 // happen in C++17, because it would mean we were computing the composite
6703 // pointer type of dependent types, which should never happen.
6704 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
6705 assert(!S.getLangOpts().CPlusPlus17 &&
6706 "computing composite pointer type of dependent types");
6707 return FunctionProtoType::ExceptionSpecInfo();
6708 }
6709
6710 // Switch over the possibilities so that people adding new values know to
6711 // update this function.
6712 switch (EST1) {
6713 case EST_None:
6714 case EST_DynamicNone:
6715 case EST_MSAny:
6716 case EST_BasicNoexcept:
6717 case EST_DependentNoexcept:
6718 case EST_NoexceptFalse:
6719 case EST_NoexceptTrue:
6720 case EST_NoThrow:
6721 llvm_unreachable("handled above");
6722
6723 case EST_Dynamic: {
6724 // This is the fun case: both exception specifications are dynamic. Form
6725 // the union of the two lists.
6726 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6727 llvm::SmallPtrSet<QualType, 8> Found;
6728 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6729 for (QualType E : Exceptions)
6730 if (Found.insert(S.Context.getCanonicalType(E)).second)
6731 ExceptionTypeStorage.push_back(E);
6732
6733 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6734 Result.Exceptions = ExceptionTypeStorage;
6735 return Result;
6736 }
6737
6738 case EST_Unevaluated:
6739 case EST_Uninstantiated:
6740 case EST_Unparsed:
6741 llvm_unreachable("shouldn't see unresolved exception specifications here");
6742 }
6743
6744 llvm_unreachable("invalid ExceptionSpecificationType");
6745 }
6746
6747 /// Find a merged pointer type and convert the two expressions to it.
6748 ///
6749 /// This finds the composite pointer type for \p E1 and \p E2 according to
6750 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
6751 /// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
6752 /// is \c true).
6753 ///
6754 /// \param Loc The location of the operator requiring these two expressions to
6755 /// be converted to the composite pointer type.
6756 ///
6757 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
FindCompositePointerType(SourceLocation Loc,Expr * & E1,Expr * & E2,bool ConvertArgs)6758 QualType Sema::FindCompositePointerType(SourceLocation Loc,
6759 Expr *&E1, Expr *&E2,
6760 bool ConvertArgs) {
6761 assert(getLangOpts().CPlusPlus && "This function assumes C++");
6762
6763 // C++1z [expr]p14:
6764 // The composite pointer type of two operands p1 and p2 having types T1
6765 // and T2
6766 QualType T1 = E1->getType(), T2 = E2->getType();
6767
6768 // where at least one is a pointer or pointer to member type or
6769 // std::nullptr_t is:
6770 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6771 T1->isNullPtrType();
6772 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6773 T2->isNullPtrType();
6774 if (!T1IsPointerLike && !T2IsPointerLike)
6775 return QualType();
6776
6777 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6778 // This can't actually happen, following the standard, but we also use this
6779 // to implement the end of [expr.conv], which hits this case.
6780 //
6781 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6782 if (T1IsPointerLike &&
6783 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6784 if (ConvertArgs)
6785 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6786 ? CK_NullToMemberPointer
6787 : CK_NullToPointer).get();
6788 return T1;
6789 }
6790 if (T2IsPointerLike &&
6791 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6792 if (ConvertArgs)
6793 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6794 ? CK_NullToMemberPointer
6795 : CK_NullToPointer).get();
6796 return T2;
6797 }
6798
6799 // Now both have to be pointers or member pointers.
6800 if (!T1IsPointerLike || !T2IsPointerLike)
6801 return QualType();
6802 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6803 "nullptr_t should be a null pointer constant");
6804
6805 struct Step {
6806 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6807 // Qualifiers to apply under the step kind.
6808 Qualifiers Quals;
6809 /// The class for a pointer-to-member; a constant array type with a bound
6810 /// (if any) for an array.
6811 const Type *ClassOrBound;
6812
6813 Step(Kind K, const Type *ClassOrBound = nullptr)
6814 : K(K), ClassOrBound(ClassOrBound) {}
6815 QualType rebuild(ASTContext &Ctx, QualType T) const {
6816 T = Ctx.getQualifiedType(T, Quals);
6817 switch (K) {
6818 case Pointer:
6819 return Ctx.getPointerType(T);
6820 case MemberPointer:
6821 return Ctx.getMemberPointerType(T, ClassOrBound);
6822 case ObjCPointer:
6823 return Ctx.getObjCObjectPointerType(T);
6824 case Array:
6825 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6826 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6827 ArrayType::Normal, 0);
6828 else
6829 return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0);
6830 }
6831 llvm_unreachable("unknown step kind");
6832 }
6833 };
6834
6835 SmallVector<Step, 8> Steps;
6836
6837 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6838 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6839 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6840 // respectively;
6841 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6842 // to member of C2 of type cv2 U2" for some non-function type U, where
6843 // C1 is reference-related to C2 or C2 is reference-related to C1, the
6844 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6845 // respectively;
6846 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6847 // T2;
6848 //
6849 // Dismantle T1 and T2 to simultaneously determine whether they are similar
6850 // and to prepare to form the cv-combined type if so.
6851 QualType Composite1 = T1;
6852 QualType Composite2 = T2;
6853 unsigned NeedConstBefore = 0;
6854 while (true) {
6855 assert(!Composite1.isNull() && !Composite2.isNull());
6856
6857 Qualifiers Q1, Q2;
6858 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
6859 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
6860
6861 // Top-level qualifiers are ignored. Merge at all lower levels.
6862 if (!Steps.empty()) {
6863 // Find the qualifier union: (approximately) the unique minimal set of
6864 // qualifiers that is compatible with both types.
6865 Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |
6866 Q2.getCVRUQualifiers());
6867
6868 // Under one level of pointer or pointer-to-member, we can change to an
6869 // unambiguous compatible address space.
6870 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6871 Quals.setAddressSpace(Q1.getAddressSpace());
6872 } else if (Steps.size() == 1) {
6873 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
6874 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
6875 if (MaybeQ1 == MaybeQ2) {
6876 // Exception for ptr size address spaces. Should be able to choose
6877 // either address space during comparison.
6878 if (isPtrSizeAddressSpace(Q1.getAddressSpace()) ||
6879 isPtrSizeAddressSpace(Q2.getAddressSpace()))
6880 MaybeQ1 = true;
6881 else
6882 return QualType(); // No unique best address space.
6883 }
6884 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6885 : Q2.getAddressSpace());
6886 } else {
6887 return QualType();
6888 }
6889
6890 // FIXME: In C, we merge __strong and none to __strong at the top level.
6891 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6892 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6893 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6894 assert(Steps.size() == 1);
6895 else
6896 return QualType();
6897
6898 // Mismatched lifetime qualifiers never compatibly include each other.
6899 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6900 Quals.setObjCLifetime(Q1.getObjCLifetime());
6901 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6902 assert(Steps.size() == 1);
6903 else
6904 return QualType();
6905
6906 Steps.back().Quals = Quals;
6907 if (Q1 != Quals || Q2 != Quals)
6908 NeedConstBefore = Steps.size() - 1;
6909 }
6910
6911 // FIXME: Can we unify the following with UnwrapSimilarTypes?
6912
6913 const ArrayType *Arr1, *Arr2;
6914 if ((Arr1 = Context.getAsArrayType(Composite1)) &&
6915 (Arr2 = Context.getAsArrayType(Composite2))) {
6916 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
6917 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
6918 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
6919 Composite1 = Arr1->getElementType();
6920 Composite2 = Arr2->getElementType();
6921 Steps.emplace_back(Step::Array, CAT1);
6922 continue;
6923 }
6924 bool IAT1 = isa<IncompleteArrayType>(Arr1);
6925 bool IAT2 = isa<IncompleteArrayType>(Arr2);
6926 if ((IAT1 && IAT2) ||
6927 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
6928 ((bool)CAT1 != (bool)CAT2) &&
6929 (Steps.empty() || Steps.back().K != Step::Array))) {
6930 // In C++20 onwards, we can unify an array of N T with an array of
6931 // a different or unknown bound. But we can't form an array whose
6932 // element type is an array of unknown bound by doing so.
6933 Composite1 = Arr1->getElementType();
6934 Composite2 = Arr2->getElementType();
6935 Steps.emplace_back(Step::Array);
6936 if (CAT1 || CAT2)
6937 NeedConstBefore = Steps.size();
6938 continue;
6939 }
6940 }
6941
6942 const PointerType *Ptr1, *Ptr2;
6943 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6944 (Ptr2 = Composite2->getAs<PointerType>())) {
6945 Composite1 = Ptr1->getPointeeType();
6946 Composite2 = Ptr2->getPointeeType();
6947 Steps.emplace_back(Step::Pointer);
6948 continue;
6949 }
6950
6951 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6952 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6953 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6954 Composite1 = ObjPtr1->getPointeeType();
6955 Composite2 = ObjPtr2->getPointeeType();
6956 Steps.emplace_back(Step::ObjCPointer);
6957 continue;
6958 }
6959
6960 const MemberPointerType *MemPtr1, *MemPtr2;
6961 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6962 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6963 Composite1 = MemPtr1->getPointeeType();
6964 Composite2 = MemPtr2->getPointeeType();
6965
6966 // At the top level, we can perform a base-to-derived pointer-to-member
6967 // conversion:
6968 //
6969 // - [...] where C1 is reference-related to C2 or C2 is
6970 // reference-related to C1
6971 //
6972 // (Note that the only kinds of reference-relatedness in scope here are
6973 // "same type or derived from".) At any other level, the class must
6974 // exactly match.
6975 const Type *Class = nullptr;
6976 QualType Cls1(MemPtr1->getClass(), 0);
6977 QualType Cls2(MemPtr2->getClass(), 0);
6978 if (Context.hasSameType(Cls1, Cls2))
6979 Class = MemPtr1->getClass();
6980 else if (Steps.empty())
6981 Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
6982 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
6983 if (!Class)
6984 return QualType();
6985
6986 Steps.emplace_back(Step::MemberPointer, Class);
6987 continue;
6988 }
6989
6990 // Special case: at the top level, we can decompose an Objective-C pointer
6991 // and a 'cv void *'. Unify the qualifiers.
6992 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
6993 Composite2->isObjCObjectPointerType()) ||
6994 (Composite1->isObjCObjectPointerType() &&
6995 Composite2->isVoidPointerType()))) {
6996 Composite1 = Composite1->getPointeeType();
6997 Composite2 = Composite2->getPointeeType();
6998 Steps.emplace_back(Step::Pointer);
6999 continue;
7000 }
7001
7002 // FIXME: block pointer types?
7003
7004 // Cannot unwrap any more types.
7005 break;
7006 }
7007
7008 // - if T1 or T2 is "pointer to noexcept function" and the other type is
7009 // "pointer to function", where the function types are otherwise the same,
7010 // "pointer to function";
7011 // - if T1 or T2 is "pointer to member of C1 of type function", the other
7012 // type is "pointer to member of C2 of type noexcept function", and C1
7013 // is reference-related to C2 or C2 is reference-related to C1, where
7014 // the function types are otherwise the same, "pointer to member of C2 of
7015 // type function" or "pointer to member of C1 of type function",
7016 // respectively;
7017 //
7018 // We also support 'noreturn' here, so as a Clang extension we generalize the
7019 // above to:
7020 //
7021 // - [Clang] If T1 and T2 are both of type "pointer to function" or
7022 // "pointer to member function" and the pointee types can be unified
7023 // by a function pointer conversion, that conversion is applied
7024 // before checking the following rules.
7025 //
7026 // We've already unwrapped down to the function types, and we want to merge
7027 // rather than just convert, so do this ourselves rather than calling
7028 // IsFunctionConversion.
7029 //
7030 // FIXME: In order to match the standard wording as closely as possible, we
7031 // currently only do this under a single level of pointers. Ideally, we would
7032 // allow this in general, and set NeedConstBefore to the relevant depth on
7033 // the side(s) where we changed anything. If we permit that, we should also
7034 // consider this conversion when determining type similarity and model it as
7035 // a qualification conversion.
7036 if (Steps.size() == 1) {
7037 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
7038 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
7039 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
7040 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
7041
7042 // The result is noreturn if both operands are.
7043 bool Noreturn =
7044 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
7045 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
7046 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
7047
7048 // The result is nothrow if both operands are.
7049 SmallVector<QualType, 8> ExceptionTypeStorage;
7050 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
7051 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
7052 ExceptionTypeStorage);
7053
7054 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
7055 FPT1->getParamTypes(), EPI1);
7056 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
7057 FPT2->getParamTypes(), EPI2);
7058 }
7059 }
7060 }
7061
7062 // There are some more conversions we can perform under exactly one pointer.
7063 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
7064 !Context.hasSameType(Composite1, Composite2)) {
7065 // - if T1 or T2 is "pointer to cv1 void" and the other type is
7066 // "pointer to cv2 T", where T is an object type or void,
7067 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
7068 if (Composite1->isVoidType() && Composite2->isObjectType())
7069 Composite2 = Composite1;
7070 else if (Composite2->isVoidType() && Composite1->isObjectType())
7071 Composite1 = Composite2;
7072 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7073 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7074 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
7075 // T1, respectively;
7076 //
7077 // The "similar type" handling covers all of this except for the "T1 is a
7078 // base class of T2" case in the definition of reference-related.
7079 else if (IsDerivedFrom(Loc, Composite1, Composite2))
7080 Composite1 = Composite2;
7081 else if (IsDerivedFrom(Loc, Composite2, Composite1))
7082 Composite2 = Composite1;
7083 }
7084
7085 // At this point, either the inner types are the same or we have failed to
7086 // find a composite pointer type.
7087 if (!Context.hasSameType(Composite1, Composite2))
7088 return QualType();
7089
7090 // Per C++ [conv.qual]p3, add 'const' to every level before the last
7091 // differing qualifier.
7092 for (unsigned I = 0; I != NeedConstBefore; ++I)
7093 Steps[I].Quals.addConst();
7094
7095 // Rebuild the composite type.
7096 QualType Composite = Composite1;
7097 for (auto &S : llvm::reverse(Steps))
7098 Composite = S.rebuild(Context, Composite);
7099
7100 if (ConvertArgs) {
7101 // Convert the expressions to the composite pointer type.
7102 InitializedEntity Entity =
7103 InitializedEntity::InitializeTemporary(Composite);
7104 InitializationKind Kind =
7105 InitializationKind::CreateCopy(Loc, SourceLocation());
7106
7107 InitializationSequence E1ToC(*this, Entity, Kind, E1);
7108 if (!E1ToC)
7109 return QualType();
7110
7111 InitializationSequence E2ToC(*this, Entity, Kind, E2);
7112 if (!E2ToC)
7113 return QualType();
7114
7115 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
7116 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
7117 if (E1Result.isInvalid())
7118 return QualType();
7119 E1 = E1Result.get();
7120
7121 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
7122 if (E2Result.isInvalid())
7123 return QualType();
7124 E2 = E2Result.get();
7125 }
7126
7127 return Composite;
7128 }
7129
MaybeBindToTemporary(Expr * E)7130 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
7131 if (!E)
7132 return ExprError();
7133
7134 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
7135
7136 // If the result is a glvalue, we shouldn't bind it.
7137 if (E->isGLValue())
7138 return E;
7139
7140 // In ARC, calls that return a retainable type can return retained,
7141 // in which case we have to insert a consuming cast.
7142 if (getLangOpts().ObjCAutoRefCount &&
7143 E->getType()->isObjCRetainableType()) {
7144
7145 bool ReturnsRetained;
7146
7147 // For actual calls, we compute this by examining the type of the
7148 // called value.
7149 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
7150 Expr *Callee = Call->getCallee()->IgnoreParens();
7151 QualType T = Callee->getType();
7152
7153 if (T == Context.BoundMemberTy) {
7154 // Handle pointer-to-members.
7155 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
7156 T = BinOp->getRHS()->getType();
7157 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
7158 T = Mem->getMemberDecl()->getType();
7159 }
7160
7161 if (const PointerType *Ptr = T->getAs<PointerType>())
7162 T = Ptr->getPointeeType();
7163 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
7164 T = Ptr->getPointeeType();
7165 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
7166 T = MemPtr->getPointeeType();
7167
7168 auto *FTy = T->castAs<FunctionType>();
7169 ReturnsRetained = FTy->getExtInfo().getProducesResult();
7170
7171 // ActOnStmtExpr arranges things so that StmtExprs of retainable
7172 // type always produce a +1 object.
7173 } else if (isa<StmtExpr>(E)) {
7174 ReturnsRetained = true;
7175
7176 // We hit this case with the lambda conversion-to-block optimization;
7177 // we don't want any extra casts here.
7178 } else if (isa<CastExpr>(E) &&
7179 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
7180 return E;
7181
7182 // For message sends and property references, we try to find an
7183 // actual method. FIXME: we should infer retention by selector in
7184 // cases where we don't have an actual method.
7185 } else {
7186 ObjCMethodDecl *D = nullptr;
7187 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
7188 D = Send->getMethodDecl();
7189 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
7190 D = BoxedExpr->getBoxingMethod();
7191 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
7192 // Don't do reclaims if we're using the zero-element array
7193 // constant.
7194 if (ArrayLit->getNumElements() == 0 &&
7195 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
7196 return E;
7197
7198 D = ArrayLit->getArrayWithObjectsMethod();
7199 } else if (ObjCDictionaryLiteral *DictLit
7200 = dyn_cast<ObjCDictionaryLiteral>(E)) {
7201 // Don't do reclaims if we're using the zero-element dictionary
7202 // constant.
7203 if (DictLit->getNumElements() == 0 &&
7204 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
7205 return E;
7206
7207 D = DictLit->getDictWithObjectsMethod();
7208 }
7209
7210 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
7211
7212 // Don't do reclaims on performSelector calls; despite their
7213 // return type, the invoked method doesn't necessarily actually
7214 // return an object.
7215 if (!ReturnsRetained &&
7216 D && D->getMethodFamily() == OMF_performSelector)
7217 return E;
7218 }
7219
7220 // Don't reclaim an object of Class type.
7221 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
7222 return E;
7223
7224 Cleanup.setExprNeedsCleanups(true);
7225
7226 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
7227 : CK_ARCReclaimReturnedObject);
7228 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
7229 VK_PRValue, FPOptionsOverride());
7230 }
7231
7232 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
7233 Cleanup.setExprNeedsCleanups(true);
7234
7235 if (!getLangOpts().CPlusPlus)
7236 return E;
7237
7238 // Search for the base element type (cf. ASTContext::getBaseElementType) with
7239 // a fast path for the common case that the type is directly a RecordType.
7240 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
7241 const RecordType *RT = nullptr;
7242 while (!RT) {
7243 switch (T->getTypeClass()) {
7244 case Type::Record:
7245 RT = cast<RecordType>(T);
7246 break;
7247 case Type::ConstantArray:
7248 case Type::IncompleteArray:
7249 case Type::VariableArray:
7250 case Type::DependentSizedArray:
7251 T = cast<ArrayType>(T)->getElementType().getTypePtr();
7252 break;
7253 default:
7254 return E;
7255 }
7256 }
7257
7258 // That should be enough to guarantee that this type is complete, if we're
7259 // not processing a decltype expression.
7260 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7261 if (RD->isInvalidDecl() || RD->isDependentContext())
7262 return E;
7263
7264 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
7265 ExpressionEvaluationContextRecord::EK_Decltype;
7266 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
7267
7268 if (Destructor) {
7269 MarkFunctionReferenced(E->getExprLoc(), Destructor);
7270 CheckDestructorAccess(E->getExprLoc(), Destructor,
7271 PDiag(diag::err_access_dtor_temp)
7272 << E->getType());
7273 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
7274 return ExprError();
7275
7276 // If destructor is trivial, we can avoid the extra copy.
7277 if (Destructor->isTrivial())
7278 return E;
7279
7280 // We need a cleanup, but we don't need to remember the temporary.
7281 Cleanup.setExprNeedsCleanups(true);
7282 }
7283
7284 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
7285 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
7286
7287 if (IsDecltype)
7288 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
7289
7290 return Bind;
7291 }
7292
7293 ExprResult
MaybeCreateExprWithCleanups(ExprResult SubExpr)7294 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
7295 if (SubExpr.isInvalid())
7296 return ExprError();
7297
7298 return MaybeCreateExprWithCleanups(SubExpr.get());
7299 }
7300
MaybeCreateExprWithCleanups(Expr * SubExpr)7301 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
7302 assert(SubExpr && "subexpression can't be null!");
7303
7304 CleanupVarDeclMarking();
7305
7306 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
7307 assert(ExprCleanupObjects.size() >= FirstCleanup);
7308 assert(Cleanup.exprNeedsCleanups() ||
7309 ExprCleanupObjects.size() == FirstCleanup);
7310 if (!Cleanup.exprNeedsCleanups())
7311 return SubExpr;
7312
7313 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
7314 ExprCleanupObjects.size() - FirstCleanup);
7315
7316 auto *E = ExprWithCleanups::Create(
7317 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
7318 DiscardCleanupsInEvaluationContext();
7319
7320 return E;
7321 }
7322
MaybeCreateStmtWithCleanups(Stmt * SubStmt)7323 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
7324 assert(SubStmt && "sub-statement can't be null!");
7325
7326 CleanupVarDeclMarking();
7327
7328 if (!Cleanup.exprNeedsCleanups())
7329 return SubStmt;
7330
7331 // FIXME: In order to attach the temporaries, wrap the statement into
7332 // a StmtExpr; currently this is only used for asm statements.
7333 // This is hacky, either create a new CXXStmtWithTemporaries statement or
7334 // a new AsmStmtWithTemporaries.
7335 CompoundStmt *CompStmt =
7336 CompoundStmt::Create(Context, SubStmt, FPOptionsOverride(),
7337 SourceLocation(), SourceLocation());
7338 Expr *E = new (Context)
7339 StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
7340 /*FIXME TemplateDepth=*/0);
7341 return MaybeCreateExprWithCleanups(E);
7342 }
7343
7344 /// Process the expression contained within a decltype. For such expressions,
7345 /// certain semantic checks on temporaries are delayed until this point, and
7346 /// are omitted for the 'topmost' call in the decltype expression. If the
7347 /// topmost call bound a temporary, strip that temporary off the expression.
ActOnDecltypeExpression(Expr * E)7348 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
7349 assert(ExprEvalContexts.back().ExprContext ==
7350 ExpressionEvaluationContextRecord::EK_Decltype &&
7351 "not in a decltype expression");
7352
7353 ExprResult Result = CheckPlaceholderExpr(E);
7354 if (Result.isInvalid())
7355 return ExprError();
7356 E = Result.get();
7357
7358 // C++11 [expr.call]p11:
7359 // If a function call is a prvalue of object type,
7360 // -- if the function call is either
7361 // -- the operand of a decltype-specifier, or
7362 // -- the right operand of a comma operator that is the operand of a
7363 // decltype-specifier,
7364 // a temporary object is not introduced for the prvalue.
7365
7366 // Recursively rebuild ParenExprs and comma expressions to strip out the
7367 // outermost CXXBindTemporaryExpr, if any.
7368 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7369 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
7370 if (SubExpr.isInvalid())
7371 return ExprError();
7372 if (SubExpr.get() == PE->getSubExpr())
7373 return E;
7374 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
7375 }
7376 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7377 if (BO->getOpcode() == BO_Comma) {
7378 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7379 if (RHS.isInvalid())
7380 return ExprError();
7381 if (RHS.get() == BO->getRHS())
7382 return E;
7383 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
7384 BO->getType(), BO->getValueKind(),
7385 BO->getObjectKind(), BO->getOperatorLoc(),
7386 BO->getFPFeatures(getLangOpts()));
7387 }
7388 }
7389
7390 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7391 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7392 : nullptr;
7393 if (TopCall)
7394 E = TopCall;
7395 else
7396 TopBind = nullptr;
7397
7398 // Disable the special decltype handling now.
7399 ExprEvalContexts.back().ExprContext =
7400 ExpressionEvaluationContextRecord::EK_Other;
7401
7402 Result = CheckUnevaluatedOperand(E);
7403 if (Result.isInvalid())
7404 return ExprError();
7405 E = Result.get();
7406
7407 // In MS mode, don't perform any extra checking of call return types within a
7408 // decltype expression.
7409 if (getLangOpts().MSVCCompat)
7410 return E;
7411
7412 // Perform the semantic checks we delayed until this point.
7413 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7414 I != N; ++I) {
7415 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7416 if (Call == TopCall)
7417 continue;
7418
7419 if (CheckCallReturnType(Call->getCallReturnType(Context),
7420 Call->getBeginLoc(), Call, Call->getDirectCallee()))
7421 return ExprError();
7422 }
7423
7424 // Now all relevant types are complete, check the destructors are accessible
7425 // and non-deleted, and annotate them on the temporaries.
7426 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7427 I != N; ++I) {
7428 CXXBindTemporaryExpr *Bind =
7429 ExprEvalContexts.back().DelayedDecltypeBinds[I];
7430 if (Bind == TopBind)
7431 continue;
7432
7433 CXXTemporary *Temp = Bind->getTemporary();
7434
7435 CXXRecordDecl *RD =
7436 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7437 CXXDestructorDecl *Destructor = LookupDestructor(RD);
7438 Temp->setDestructor(Destructor);
7439
7440 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7441 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7442 PDiag(diag::err_access_dtor_temp)
7443 << Bind->getType());
7444 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7445 return ExprError();
7446
7447 // We need a cleanup, but we don't need to remember the temporary.
7448 Cleanup.setExprNeedsCleanups(true);
7449 }
7450
7451 // Possibly strip off the top CXXBindTemporaryExpr.
7452 return E;
7453 }
7454
7455 /// Note a set of 'operator->' functions that were used for a member access.
noteOperatorArrows(Sema & S,ArrayRef<FunctionDecl * > OperatorArrows)7456 static void noteOperatorArrows(Sema &S,
7457 ArrayRef<FunctionDecl *> OperatorArrows) {
7458 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7459 // FIXME: Make this configurable?
7460 unsigned Limit = 9;
7461 if (OperatorArrows.size() > Limit) {
7462 // Produce Limit-1 normal notes and one 'skipping' note.
7463 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7464 SkipCount = OperatorArrows.size() - (Limit - 1);
7465 }
7466
7467 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7468 if (I == SkipStart) {
7469 S.Diag(OperatorArrows[I]->getLocation(),
7470 diag::note_operator_arrows_suppressed)
7471 << SkipCount;
7472 I += SkipCount;
7473 } else {
7474 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7475 << OperatorArrows[I]->getCallResultType();
7476 ++I;
7477 }
7478 }
7479 }
7480
ActOnStartCXXMemberReference(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,ParsedType & ObjectType,bool & MayBePseudoDestructor)7481 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
7482 SourceLocation OpLoc,
7483 tok::TokenKind OpKind,
7484 ParsedType &ObjectType,
7485 bool &MayBePseudoDestructor) {
7486 // Since this might be a postfix expression, get rid of ParenListExprs.
7487 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
7488 if (Result.isInvalid()) return ExprError();
7489 Base = Result.get();
7490
7491 Result = CheckPlaceholderExpr(Base);
7492 if (Result.isInvalid()) return ExprError();
7493 Base = Result.get();
7494
7495 QualType BaseType = Base->getType();
7496 MayBePseudoDestructor = false;
7497 if (BaseType->isDependentType()) {
7498 // If we have a pointer to a dependent type and are using the -> operator,
7499 // the object type is the type that the pointer points to. We might still
7500 // have enough information about that type to do something useful.
7501 if (OpKind == tok::arrow)
7502 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7503 BaseType = Ptr->getPointeeType();
7504
7505 ObjectType = ParsedType::make(BaseType);
7506 MayBePseudoDestructor = true;
7507 return Base;
7508 }
7509
7510 // C++ [over.match.oper]p8:
7511 // [...] When operator->returns, the operator-> is applied to the value
7512 // returned, with the original second operand.
7513 if (OpKind == tok::arrow) {
7514 QualType StartingType = BaseType;
7515 bool NoArrowOperatorFound = false;
7516 bool FirstIteration = true;
7517 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
7518 // The set of types we've considered so far.
7519 llvm::SmallPtrSet<CanQualType,8> CTypes;
7520 SmallVector<FunctionDecl*, 8> OperatorArrows;
7521 CTypes.insert(Context.getCanonicalType(BaseType));
7522
7523 while (BaseType->isRecordType()) {
7524 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7525 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
7526 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
7527 noteOperatorArrows(*this, OperatorArrows);
7528 Diag(OpLoc, diag::note_operator_arrow_depth)
7529 << getLangOpts().ArrowDepth;
7530 return ExprError();
7531 }
7532
7533 Result = BuildOverloadedArrowExpr(
7534 S, Base, OpLoc,
7535 // When in a template specialization and on the first loop iteration,
7536 // potentially give the default diagnostic (with the fixit in a
7537 // separate note) instead of having the error reported back to here
7538 // and giving a diagnostic with a fixit attached to the error itself.
7539 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7540 ? nullptr
7541 : &NoArrowOperatorFound);
7542 if (Result.isInvalid()) {
7543 if (NoArrowOperatorFound) {
7544 if (FirstIteration) {
7545 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7546 << BaseType << 1 << Base->getSourceRange()
7547 << FixItHint::CreateReplacement(OpLoc, ".");
7548 OpKind = tok::period;
7549 break;
7550 }
7551 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7552 << BaseType << Base->getSourceRange();
7553 CallExpr *CE = dyn_cast<CallExpr>(Base);
7554 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7555 Diag(CD->getBeginLoc(),
7556 diag::note_member_reference_arrow_from_operator_arrow);
7557 }
7558 }
7559 return ExprError();
7560 }
7561 Base = Result.get();
7562 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7563 OperatorArrows.push_back(OpCall->getDirectCallee());
7564 BaseType = Base->getType();
7565 CanQualType CBaseType = Context.getCanonicalType(BaseType);
7566 if (!CTypes.insert(CBaseType).second) {
7567 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7568 noteOperatorArrows(*this, OperatorArrows);
7569 return ExprError();
7570 }
7571 FirstIteration = false;
7572 }
7573
7574 if (OpKind == tok::arrow) {
7575 if (BaseType->isPointerType())
7576 BaseType = BaseType->getPointeeType();
7577 else if (auto *AT = Context.getAsArrayType(BaseType))
7578 BaseType = AT->getElementType();
7579 }
7580 }
7581
7582 // Objective-C properties allow "." access on Objective-C pointer types,
7583 // so adjust the base type to the object type itself.
7584 if (BaseType->isObjCObjectPointerType())
7585 BaseType = BaseType->getPointeeType();
7586
7587 // C++ [basic.lookup.classref]p2:
7588 // [...] If the type of the object expression is of pointer to scalar
7589 // type, the unqualified-id is looked up in the context of the complete
7590 // postfix-expression.
7591 //
7592 // This also indicates that we could be parsing a pseudo-destructor-name.
7593 // Note that Objective-C class and object types can be pseudo-destructor
7594 // expressions or normal member (ivar or property) access expressions, and
7595 // it's legal for the type to be incomplete if this is a pseudo-destructor
7596 // call. We'll do more incomplete-type checks later in the lookup process,
7597 // so just skip this check for ObjC types.
7598 if (!BaseType->isRecordType()) {
7599 ObjectType = ParsedType::make(BaseType);
7600 MayBePseudoDestructor = true;
7601 return Base;
7602 }
7603
7604 // The object type must be complete (or dependent), or
7605 // C++11 [expr.prim.general]p3:
7606 // Unlike the object expression in other contexts, *this is not required to
7607 // be of complete type for purposes of class member access (5.2.5) outside
7608 // the member function body.
7609 if (!BaseType->isDependentType() &&
7610 !isThisOutsideMemberFunctionBody(BaseType) &&
7611 RequireCompleteType(OpLoc, BaseType,
7612 diag::err_incomplete_member_access)) {
7613 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
7614 }
7615
7616 // C++ [basic.lookup.classref]p2:
7617 // If the id-expression in a class member access (5.2.5) is an
7618 // unqualified-id, and the type of the object expression is of a class
7619 // type C (or of pointer to a class type C), the unqualified-id is looked
7620 // up in the scope of class C. [...]
7621 ObjectType = ParsedType::make(BaseType);
7622 return Base;
7623 }
7624
CheckArrow(Sema & S,QualType & ObjectType,Expr * & Base,tok::TokenKind & OpKind,SourceLocation OpLoc)7625 static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
7626 tok::TokenKind &OpKind, SourceLocation OpLoc) {
7627 if (Base->hasPlaceholderType()) {
7628 ExprResult result = S.CheckPlaceholderExpr(Base);
7629 if (result.isInvalid()) return true;
7630 Base = result.get();
7631 }
7632 ObjectType = Base->getType();
7633
7634 // C++ [expr.pseudo]p2:
7635 // The left-hand side of the dot operator shall be of scalar type. The
7636 // left-hand side of the arrow operator shall be of pointer to scalar type.
7637 // This scalar type is the object type.
7638 // Note that this is rather different from the normal handling for the
7639 // arrow operator.
7640 if (OpKind == tok::arrow) {
7641 // The operator requires a prvalue, so perform lvalue conversions.
7642 // Only do this if we might plausibly end with a pointer, as otherwise
7643 // this was likely to be intended to be a '.'.
7644 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
7645 ObjectType->isFunctionType()) {
7646 ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base);
7647 if (BaseResult.isInvalid())
7648 return true;
7649 Base = BaseResult.get();
7650 ObjectType = Base->getType();
7651 }
7652
7653 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7654 ObjectType = Ptr->getPointeeType();
7655 } else if (!Base->isTypeDependent()) {
7656 // The user wrote "p->" when they probably meant "p."; fix it.
7657 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7658 << ObjectType << true
7659 << FixItHint::CreateReplacement(OpLoc, ".");
7660 if (S.isSFINAEContext())
7661 return true;
7662
7663 OpKind = tok::period;
7664 }
7665 }
7666
7667 return false;
7668 }
7669
7670 /// Check if it's ok to try and recover dot pseudo destructor calls on
7671 /// pointer objects.
7672 static bool
canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema & SemaRef,QualType DestructedType)7673 canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
7674 QualType DestructedType) {
7675 // If this is a record type, check if its destructor is callable.
7676 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
7677 if (RD->hasDefinition())
7678 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
7679 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
7680 return false;
7681 }
7682
7683 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7684 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7685 DestructedType->isVectorType();
7686 }
7687
BuildPseudoDestructorExpr(Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,const CXXScopeSpec & SS,TypeSourceInfo * ScopeTypeInfo,SourceLocation CCLoc,SourceLocation TildeLoc,PseudoDestructorTypeStorage Destructed)7688 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
7689 SourceLocation OpLoc,
7690 tok::TokenKind OpKind,
7691 const CXXScopeSpec &SS,
7692 TypeSourceInfo *ScopeTypeInfo,
7693 SourceLocation CCLoc,
7694 SourceLocation TildeLoc,
7695 PseudoDestructorTypeStorage Destructed) {
7696 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
7697
7698 QualType ObjectType;
7699 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7700 return ExprError();
7701
7702 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7703 !ObjectType->isVectorType()) {
7704 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
7705 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
7706 else {
7707 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7708 << ObjectType << Base->getSourceRange();
7709 return ExprError();
7710 }
7711 }
7712
7713 // C++ [expr.pseudo]p2:
7714 // [...] The cv-unqualified versions of the object type and of the type
7715 // designated by the pseudo-destructor-name shall be the same type.
7716 if (DestructedTypeInfo) {
7717 QualType DestructedType = DestructedTypeInfo->getType();
7718 SourceLocation DestructedTypeStart
7719 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
7720 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7721 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
7722 // Detect dot pseudo destructor calls on pointer objects, e.g.:
7723 // Foo *foo;
7724 // foo.~Foo();
7725 if (OpKind == tok::period && ObjectType->isPointerType() &&
7726 Context.hasSameUnqualifiedType(DestructedType,
7727 ObjectType->getPointeeType())) {
7728 auto Diagnostic =
7729 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7730 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
7731
7732 // Issue a fixit only when the destructor is valid.
7733 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
7734 *this, DestructedType))
7735 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
7736
7737 // Recover by setting the object type to the destructed type and the
7738 // operator to '->'.
7739 ObjectType = DestructedType;
7740 OpKind = tok::arrow;
7741 } else {
7742 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7743 << ObjectType << DestructedType << Base->getSourceRange()
7744 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7745
7746 // Recover by setting the destructed type to the object type.
7747 DestructedType = ObjectType;
7748 DestructedTypeInfo =
7749 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7750 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7751 }
7752 } else if (DestructedType.getObjCLifetime() !=
7753 ObjectType.getObjCLifetime()) {
7754
7755 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7756 // Okay: just pretend that the user provided the correctly-qualified
7757 // type.
7758 } else {
7759 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7760 << ObjectType << DestructedType << Base->getSourceRange()
7761 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7762 }
7763
7764 // Recover by setting the destructed type to the object type.
7765 DestructedType = ObjectType;
7766 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7767 DestructedTypeStart);
7768 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7769 }
7770 }
7771 }
7772
7773 // C++ [expr.pseudo]p2:
7774 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7775 // form
7776 //
7777 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7778 //
7779 // shall designate the same scalar type.
7780 if (ScopeTypeInfo) {
7781 QualType ScopeType = ScopeTypeInfo->getType();
7782 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
7783 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
7784
7785 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
7786 diag::err_pseudo_dtor_type_mismatch)
7787 << ObjectType << ScopeType << Base->getSourceRange()
7788 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
7789
7790 ScopeType = QualType();
7791 ScopeTypeInfo = nullptr;
7792 }
7793 }
7794
7795 Expr *Result
7796 = new (Context) CXXPseudoDestructorExpr(Context, Base,
7797 OpKind == tok::arrow, OpLoc,
7798 SS.getWithLocInContext(Context),
7799 ScopeTypeInfo,
7800 CCLoc,
7801 TildeLoc,
7802 Destructed);
7803
7804 return Result;
7805 }
7806
ActOnPseudoDestructorExpr(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,CXXScopeSpec & SS,UnqualifiedId & FirstTypeName,SourceLocation CCLoc,SourceLocation TildeLoc,UnqualifiedId & SecondTypeName)7807 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7808 SourceLocation OpLoc,
7809 tok::TokenKind OpKind,
7810 CXXScopeSpec &SS,
7811 UnqualifiedId &FirstTypeName,
7812 SourceLocation CCLoc,
7813 SourceLocation TildeLoc,
7814 UnqualifiedId &SecondTypeName) {
7815 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7816 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7817 "Invalid first type name in pseudo-destructor");
7818 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7819 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7820 "Invalid second type name in pseudo-destructor");
7821
7822 QualType ObjectType;
7823 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7824 return ExprError();
7825
7826 // Compute the object type that we should use for name lookup purposes. Only
7827 // record types and dependent types matter.
7828 ParsedType ObjectTypePtrForLookup;
7829 if (!SS.isSet()) {
7830 if (ObjectType->isRecordType())
7831 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7832 else if (ObjectType->isDependentType())
7833 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7834 }
7835
7836 // Convert the name of the type being destructed (following the ~) into a
7837 // type (with source-location information).
7838 QualType DestructedType;
7839 TypeSourceInfo *DestructedTypeInfo = nullptr;
7840 PseudoDestructorTypeStorage Destructed;
7841 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7842 ParsedType T = getTypeName(*SecondTypeName.Identifier,
7843 SecondTypeName.StartLocation,
7844 S, &SS, true, false, ObjectTypePtrForLookup,
7845 /*IsCtorOrDtorName*/true);
7846 if (!T &&
7847 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7848 (!SS.isSet() && ObjectType->isDependentType()))) {
7849 // The name of the type being destroyed is a dependent name, and we
7850 // couldn't find anything useful in scope. Just store the identifier and
7851 // it's location, and we'll perform (qualified) name lookup again at
7852 // template instantiation time.
7853 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7854 SecondTypeName.StartLocation);
7855 } else if (!T) {
7856 Diag(SecondTypeName.StartLocation,
7857 diag::err_pseudo_dtor_destructor_non_type)
7858 << SecondTypeName.Identifier << ObjectType;
7859 if (isSFINAEContext())
7860 return ExprError();
7861
7862 // Recover by assuming we had the right type all along.
7863 DestructedType = ObjectType;
7864 } else
7865 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7866 } else {
7867 // Resolve the template-id to a type.
7868 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7869 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7870 TemplateId->NumArgs);
7871 TypeResult T = ActOnTemplateIdType(S,
7872 SS,
7873 TemplateId->TemplateKWLoc,
7874 TemplateId->Template,
7875 TemplateId->Name,
7876 TemplateId->TemplateNameLoc,
7877 TemplateId->LAngleLoc,
7878 TemplateArgsPtr,
7879 TemplateId->RAngleLoc,
7880 /*IsCtorOrDtorName*/true);
7881 if (T.isInvalid() || !T.get()) {
7882 // Recover by assuming we had the right type all along.
7883 DestructedType = ObjectType;
7884 } else
7885 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7886 }
7887
7888 // If we've performed some kind of recovery, (re-)build the type source
7889 // information.
7890 if (!DestructedType.isNull()) {
7891 if (!DestructedTypeInfo)
7892 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7893 SecondTypeName.StartLocation);
7894 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7895 }
7896
7897 // Convert the name of the scope type (the type prior to '::') into a type.
7898 TypeSourceInfo *ScopeTypeInfo = nullptr;
7899 QualType ScopeType;
7900 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7901 FirstTypeName.Identifier) {
7902 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7903 ParsedType T = getTypeName(*FirstTypeName.Identifier,
7904 FirstTypeName.StartLocation,
7905 S, &SS, true, false, ObjectTypePtrForLookup,
7906 /*IsCtorOrDtorName*/true);
7907 if (!T) {
7908 Diag(FirstTypeName.StartLocation,
7909 diag::err_pseudo_dtor_destructor_non_type)
7910 << FirstTypeName.Identifier << ObjectType;
7911
7912 if (isSFINAEContext())
7913 return ExprError();
7914
7915 // Just drop this type. It's unnecessary anyway.
7916 ScopeType = QualType();
7917 } else
7918 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7919 } else {
7920 // Resolve the template-id to a type.
7921 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7922 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7923 TemplateId->NumArgs);
7924 TypeResult T = ActOnTemplateIdType(S,
7925 SS,
7926 TemplateId->TemplateKWLoc,
7927 TemplateId->Template,
7928 TemplateId->Name,
7929 TemplateId->TemplateNameLoc,
7930 TemplateId->LAngleLoc,
7931 TemplateArgsPtr,
7932 TemplateId->RAngleLoc,
7933 /*IsCtorOrDtorName*/true);
7934 if (T.isInvalid() || !T.get()) {
7935 // Recover by dropping this type.
7936 ScopeType = QualType();
7937 } else
7938 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7939 }
7940 }
7941
7942 if (!ScopeType.isNull() && !ScopeTypeInfo)
7943 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7944 FirstTypeName.StartLocation);
7945
7946
7947 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7948 ScopeTypeInfo, CCLoc, TildeLoc,
7949 Destructed);
7950 }
7951
ActOnPseudoDestructorExpr(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,SourceLocation TildeLoc,const DeclSpec & DS)7952 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7953 SourceLocation OpLoc,
7954 tok::TokenKind OpKind,
7955 SourceLocation TildeLoc,
7956 const DeclSpec& DS) {
7957 QualType ObjectType;
7958 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7959 return ExprError();
7960
7961 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
7962 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
7963 return true;
7964 }
7965
7966 QualType T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
7967
7968 TypeLocBuilder TLB;
7969 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7970 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
7971 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
7972 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7973 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7974
7975 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7976 nullptr, SourceLocation(), TildeLoc,
7977 Destructed);
7978 }
7979
BuildCXXMemberCallExpr(Expr * E,NamedDecl * FoundDecl,CXXConversionDecl * Method,bool HadMultipleCandidates)7980 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
7981 CXXConversionDecl *Method,
7982 bool HadMultipleCandidates) {
7983 // Convert the expression to match the conversion function's implicit object
7984 // parameter.
7985 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7986 FoundDecl, Method);
7987 if (Exp.isInvalid())
7988 return true;
7989
7990 if (Method->getParent()->isLambda() &&
7991 Method->getConversionType()->isBlockPointerType()) {
7992 // This is a lambda conversion to block pointer; check if the argument
7993 // was a LambdaExpr.
7994 Expr *SubE = E;
7995 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7996 if (CE && CE->getCastKind() == CK_NoOp)
7997 SubE = CE->getSubExpr();
7998 SubE = SubE->IgnoreParens();
7999 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
8000 SubE = BE->getSubExpr();
8001 if (isa<LambdaExpr>(SubE)) {
8002 // For the conversion to block pointer on a lambda expression, we
8003 // construct a special BlockLiteral instead; this doesn't really make
8004 // a difference in ARC, but outside of ARC the resulting block literal
8005 // follows the normal lifetime rules for block literals instead of being
8006 // autoreleased.
8007 PushExpressionEvaluationContext(
8008 ExpressionEvaluationContext::PotentiallyEvaluated);
8009 ExprResult BlockExp = BuildBlockForLambdaConversion(
8010 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
8011 PopExpressionEvaluationContext();
8012
8013 // FIXME: This note should be produced by a CodeSynthesisContext.
8014 if (BlockExp.isInvalid())
8015 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
8016 return BlockExp;
8017 }
8018 }
8019
8020 MemberExpr *ME =
8021 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
8022 NestedNameSpecifierLoc(), SourceLocation(), Method,
8023 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
8024 HadMultipleCandidates, DeclarationNameInfo(),
8025 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
8026
8027 QualType ResultType = Method->getReturnType();
8028 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8029 ResultType = ResultType.getNonLValueExprType(Context);
8030
8031 CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
8032 Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc(),
8033 CurFPFeatureOverrides());
8034
8035 if (CheckFunctionCall(Method, CE,
8036 Method->getType()->castAs<FunctionProtoType>()))
8037 return ExprError();
8038
8039 return CheckForImmediateInvocation(CE, CE->getMethodDecl());
8040 }
8041
BuildCXXNoexceptExpr(SourceLocation KeyLoc,Expr * Operand,SourceLocation RParen)8042 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8043 SourceLocation RParen) {
8044 // If the operand is an unresolved lookup expression, the expression is ill-
8045 // formed per [over.over]p1, because overloaded function names cannot be used
8046 // without arguments except in explicit contexts.
8047 ExprResult R = CheckPlaceholderExpr(Operand);
8048 if (R.isInvalid())
8049 return R;
8050
8051 R = CheckUnevaluatedOperand(R.get());
8052 if (R.isInvalid())
8053 return ExprError();
8054
8055 Operand = R.get();
8056
8057 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
8058 Operand->HasSideEffects(Context, false)) {
8059 // The expression operand for noexcept is in an unevaluated expression
8060 // context, so side effects could result in unintended consequences.
8061 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8062 }
8063
8064 CanThrowResult CanThrow = canThrow(Operand);
8065 return new (Context)
8066 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
8067 }
8068
ActOnNoexceptExpr(SourceLocation KeyLoc,SourceLocation,Expr * Operand,SourceLocation RParen)8069 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
8070 Expr *Operand, SourceLocation RParen) {
8071 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
8072 }
8073
MaybeDecrementCount(Expr * E,llvm::DenseMap<const VarDecl *,int> & RefsMinusAssignments)8074 static void MaybeDecrementCount(
8075 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
8076 DeclRefExpr *LHS = nullptr;
8077 bool IsCompoundAssign = false;
8078 bool isIncrementDecrementUnaryOp = false;
8079 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8080 if (BO->getLHS()->getType()->isDependentType() ||
8081 BO->getRHS()->getType()->isDependentType()) {
8082 if (BO->getOpcode() != BO_Assign)
8083 return;
8084 } else if (!BO->isAssignmentOp())
8085 return;
8086 else
8087 IsCompoundAssign = BO->isCompoundAssignmentOp();
8088 LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
8089 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8090 if (COCE->getOperator() != OO_Equal)
8091 return;
8092 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
8093 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8094 if (!UO->isIncrementDecrementOp())
8095 return;
8096 isIncrementDecrementUnaryOp = true;
8097 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
8098 }
8099 if (!LHS)
8100 return;
8101 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
8102 if (!VD)
8103 return;
8104 // Don't decrement RefsMinusAssignments if volatile variable with compound
8105 // assignment (+=, ...) or increment/decrement unary operator to avoid
8106 // potential unused-but-set-variable warning.
8107 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
8108 VD->getType().isVolatileQualified())
8109 return;
8110 auto iter = RefsMinusAssignments.find(VD);
8111 if (iter == RefsMinusAssignments.end())
8112 return;
8113 iter->getSecond()--;
8114 }
8115
8116 /// Perform the conversions required for an expression used in a
8117 /// context that ignores the result.
IgnoredValueConversions(Expr * E)8118 ExprResult Sema::IgnoredValueConversions(Expr *E) {
8119 MaybeDecrementCount(E, RefsMinusAssignments);
8120
8121 if (E->hasPlaceholderType()) {
8122 ExprResult result = CheckPlaceholderExpr(E);
8123 if (result.isInvalid()) return E;
8124 E = result.get();
8125 }
8126
8127 // C99 6.3.2.1:
8128 // [Except in specific positions,] an lvalue that does not have
8129 // array type is converted to the value stored in the
8130 // designated object (and is no longer an lvalue).
8131 if (E->isPRValue()) {
8132 // In C, function designators (i.e. expressions of function type)
8133 // are r-values, but we still want to do function-to-pointer decay
8134 // on them. This is both technically correct and convenient for
8135 // some clients.
8136 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
8137 return DefaultFunctionArrayConversion(E);
8138
8139 return E;
8140 }
8141
8142 if (getLangOpts().CPlusPlus) {
8143 // The C++11 standard defines the notion of a discarded-value expression;
8144 // normally, we don't need to do anything to handle it, but if it is a
8145 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
8146 // conversion.
8147 if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) {
8148 ExprResult Res = DefaultLvalueConversion(E);
8149 if (Res.isInvalid())
8150 return E;
8151 E = Res.get();
8152 } else {
8153 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8154 // it occurs as a discarded-value expression.
8155 CheckUnusedVolatileAssignment(E);
8156 }
8157
8158 // C++1z:
8159 // If the expression is a prvalue after this optional conversion, the
8160 // temporary materialization conversion is applied.
8161 //
8162 // We skip this step: IR generation is able to synthesize the storage for
8163 // itself in the aggregate case, and adding the extra node to the AST is
8164 // just clutter.
8165 // FIXME: We don't emit lifetime markers for the temporaries due to this.
8166 // FIXME: Do any other AST consumers care about this?
8167 return E;
8168 }
8169
8170 // GCC seems to also exclude expressions of incomplete enum type.
8171 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
8172 if (!T->getDecl()->isComplete()) {
8173 // FIXME: stupid workaround for a codegen bug!
8174 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
8175 return E;
8176 }
8177 }
8178
8179 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
8180 if (Res.isInvalid())
8181 return E;
8182 E = Res.get();
8183
8184 if (!E->getType()->isVoidType())
8185 RequireCompleteType(E->getExprLoc(), E->getType(),
8186 diag::err_incomplete_type);
8187 return E;
8188 }
8189
CheckUnevaluatedOperand(Expr * E)8190 ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {
8191 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8192 // it occurs as an unevaluated operand.
8193 CheckUnusedVolatileAssignment(E);
8194
8195 return E;
8196 }
8197
8198 // If we can unambiguously determine whether Var can never be used
8199 // in a constant expression, return true.
8200 // - if the variable and its initializer are non-dependent, then
8201 // we can unambiguously check if the variable is a constant expression.
8202 // - if the initializer is not value dependent - we can determine whether
8203 // it can be used to initialize a constant expression. If Init can not
8204 // be used to initialize a constant expression we conclude that Var can
8205 // never be a constant expression.
8206 // - FXIME: if the initializer is dependent, we can still do some analysis and
8207 // identify certain cases unambiguously as non-const by using a Visitor:
8208 // - such as those that involve odr-use of a ParmVarDecl, involve a new
8209 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
VariableCanNeverBeAConstantExpression(VarDecl * Var,ASTContext & Context)8210 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
8211 ASTContext &Context) {
8212 if (isa<ParmVarDecl>(Var)) return true;
8213 const VarDecl *DefVD = nullptr;
8214
8215 // If there is no initializer - this can not be a constant expression.
8216 if (!Var->getAnyInitializer(DefVD)) return true;
8217 assert(DefVD);
8218 if (DefVD->isWeak()) return false;
8219 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
8220
8221 Expr *Init = cast<Expr>(Eval->Value);
8222
8223 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
8224 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
8225 // of value-dependent expressions, and use it here to determine whether the
8226 // initializer is a potential constant expression.
8227 return false;
8228 }
8229
8230 return !Var->isUsableInConstantExpressions(Context);
8231 }
8232
8233 /// Check if the current lambda has any potential captures
8234 /// that must be captured by any of its enclosing lambdas that are ready to
8235 /// capture. If there is a lambda that can capture a nested
8236 /// potential-capture, go ahead and do so. Also, check to see if any
8237 /// variables are uncaptureable or do not involve an odr-use so do not
8238 /// need to be captured.
8239
CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(Expr * const FE,LambdaScopeInfo * const CurrentLSI,Sema & S)8240 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
8241 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
8242
8243 assert(!S.isUnevaluatedContext());
8244 assert(S.CurContext->isDependentContext());
8245 #ifndef NDEBUG
8246 DeclContext *DC = S.CurContext;
8247 while (DC && isa<CapturedDecl>(DC))
8248 DC = DC->getParent();
8249 assert(
8250 CurrentLSI->CallOperator == DC &&
8251 "The current call operator must be synchronized with Sema's CurContext");
8252 #endif // NDEBUG
8253
8254 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
8255
8256 // All the potentially captureable variables in the current nested
8257 // lambda (within a generic outer lambda), must be captured by an
8258 // outer lambda that is enclosed within a non-dependent context.
8259 CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) {
8260 // If the variable is clearly identified as non-odr-used and the full
8261 // expression is not instantiation dependent, only then do we not
8262 // need to check enclosing lambda's for speculative captures.
8263 // For e.g.:
8264 // Even though 'x' is not odr-used, it should be captured.
8265 // int test() {
8266 // const int x = 10;
8267 // auto L = [=](auto a) {
8268 // (void) +x + a;
8269 // };
8270 // }
8271 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
8272 !IsFullExprInstantiationDependent)
8273 return;
8274
8275 // If we have a capture-capable lambda for the variable, go ahead and
8276 // capture the variable in that lambda (and all its enclosing lambdas).
8277 if (const Optional<unsigned> Index =
8278 getStackIndexOfNearestEnclosingCaptureCapableLambda(
8279 S.FunctionScopes, Var, S))
8280 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
8281 const bool IsVarNeverAConstantExpression =
8282 VariableCanNeverBeAConstantExpression(Var, S.Context);
8283 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
8284 // This full expression is not instantiation dependent or the variable
8285 // can not be used in a constant expression - which means
8286 // this variable must be odr-used here, so diagnose a
8287 // capture violation early, if the variable is un-captureable.
8288 // This is purely for diagnosing errors early. Otherwise, this
8289 // error would get diagnosed when the lambda becomes capture ready.
8290 QualType CaptureType, DeclRefType;
8291 SourceLocation ExprLoc = VarExpr->getExprLoc();
8292 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8293 /*EllipsisLoc*/ SourceLocation(),
8294 /*BuildAndDiagnose*/false, CaptureType,
8295 DeclRefType, nullptr)) {
8296 // We will never be able to capture this variable, and we need
8297 // to be able to in any and all instantiations, so diagnose it.
8298 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8299 /*EllipsisLoc*/ SourceLocation(),
8300 /*BuildAndDiagnose*/true, CaptureType,
8301 DeclRefType, nullptr);
8302 }
8303 }
8304 });
8305
8306 // Check if 'this' needs to be captured.
8307 if (CurrentLSI->hasPotentialThisCapture()) {
8308 // If we have a capture-capable lambda for 'this', go ahead and capture
8309 // 'this' in that lambda (and all its enclosing lambdas).
8310 if (const Optional<unsigned> Index =
8311 getStackIndexOfNearestEnclosingCaptureCapableLambda(
8312 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
8313 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
8314 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
8315 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
8316 &FunctionScopeIndexOfCapturableLambda);
8317 }
8318 }
8319
8320 // Reset all the potential captures at the end of each full-expression.
8321 CurrentLSI->clearPotentialCaptures();
8322 }
8323
attemptRecovery(Sema & SemaRef,const TypoCorrectionConsumer & Consumer,const TypoCorrection & TC)8324 static ExprResult attemptRecovery(Sema &SemaRef,
8325 const TypoCorrectionConsumer &Consumer,
8326 const TypoCorrection &TC) {
8327 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
8328 Consumer.getLookupResult().getLookupKind());
8329 const CXXScopeSpec *SS = Consumer.getSS();
8330 CXXScopeSpec NewSS;
8331
8332 // Use an approprate CXXScopeSpec for building the expr.
8333 if (auto *NNS = TC.getCorrectionSpecifier())
8334 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
8335 else if (SS && !TC.WillReplaceSpecifier())
8336 NewSS = *SS;
8337
8338 if (auto *ND = TC.getFoundDecl()) {
8339 R.setLookupName(ND->getDeclName());
8340 R.addDecl(ND);
8341 if (ND->isCXXClassMember()) {
8342 // Figure out the correct naming class to add to the LookupResult.
8343 CXXRecordDecl *Record = nullptr;
8344 if (auto *NNS = TC.getCorrectionSpecifier())
8345 Record = NNS->getAsType()->getAsCXXRecordDecl();
8346 if (!Record)
8347 Record =
8348 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
8349 if (Record)
8350 R.setNamingClass(Record);
8351
8352 // Detect and handle the case where the decl might be an implicit
8353 // member.
8354 bool MightBeImplicitMember;
8355 if (!Consumer.isAddressOfOperand())
8356 MightBeImplicitMember = true;
8357 else if (!NewSS.isEmpty())
8358 MightBeImplicitMember = false;
8359 else if (R.isOverloadedResult())
8360 MightBeImplicitMember = false;
8361 else if (R.isUnresolvableResult())
8362 MightBeImplicitMember = true;
8363 else
8364 MightBeImplicitMember = isa<FieldDecl>(ND) ||
8365 isa<IndirectFieldDecl>(ND) ||
8366 isa<MSPropertyDecl>(ND);
8367
8368 if (MightBeImplicitMember)
8369 return SemaRef.BuildPossibleImplicitMemberExpr(
8370 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
8371 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
8372 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
8373 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
8374 Ivar->getIdentifier());
8375 }
8376 }
8377
8378 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
8379 /*AcceptInvalidDecl*/ true);
8380 }
8381
8382 namespace {
8383 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
8384 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
8385
8386 public:
FindTypoExprs(llvm::SmallSetVector<TypoExpr *,2> & TypoExprs)8387 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8388 : TypoExprs(TypoExprs) {}
VisitTypoExpr(TypoExpr * TE)8389 bool VisitTypoExpr(TypoExpr *TE) {
8390 TypoExprs.insert(TE);
8391 return true;
8392 }
8393 };
8394
8395 class TransformTypos : public TreeTransform<TransformTypos> {
8396 typedef TreeTransform<TransformTypos> BaseTransform;
8397
8398 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8399 // process of being initialized.
8400 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
8401 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
8402 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
8403 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
8404
8405 /// Emit diagnostics for all of the TypoExprs encountered.
8406 ///
8407 /// If the TypoExprs were successfully corrected, then the diagnostics should
8408 /// suggest the corrections. Otherwise the diagnostics will not suggest
8409 /// anything (having been passed an empty TypoCorrection).
8410 ///
8411 /// If we've failed to correct due to ambiguous corrections, we need to
8412 /// be sure to pass empty corrections and replacements. Otherwise it's
8413 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8414 /// and we don't want to report those diagnostics.
EmitAllDiagnostics(bool IsAmbiguous)8415 void EmitAllDiagnostics(bool IsAmbiguous) {
8416 for (TypoExpr *TE : TypoExprs) {
8417 auto &State = SemaRef.getTypoExprState(TE);
8418 if (State.DiagHandler) {
8419 TypoCorrection TC = IsAmbiguous
8420 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
8421 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
8422
8423 // Extract the NamedDecl from the transformed TypoExpr and add it to the
8424 // TypoCorrection, replacing the existing decls. This ensures the right
8425 // NamedDecl is used in diagnostics e.g. in the case where overload
8426 // resolution was used to select one from several possible decls that
8427 // had been stored in the TypoCorrection.
8428 if (auto *ND = getDeclFromExpr(
8429 Replacement.isInvalid() ? nullptr : Replacement.get()))
8430 TC.setCorrectionDecl(ND);
8431
8432 State.DiagHandler(TC);
8433 }
8434 SemaRef.clearDelayedTypo(TE);
8435 }
8436 }
8437
8438 /// Try to advance the typo correction state of the first unfinished TypoExpr.
8439 /// We allow advancement of the correction stream by removing it from the
8440 /// TransformCache which allows `TransformTypoExpr` to advance during the
8441 /// next transformation attempt.
8442 ///
8443 /// Any substitution attempts for the previous TypoExprs (which must have been
8444 /// finished) will need to be retried since it's possible that they will now
8445 /// be invalid given the latest advancement.
8446 ///
8447 /// We need to be sure that we're making progress - it's possible that the
8448 /// tree is so malformed that the transform never makes it to the
8449 /// `TransformTypoExpr`.
8450 ///
8451 /// Returns true if there are any untried correction combinations.
CheckAndAdvanceTypoExprCorrectionStreams()8452 bool CheckAndAdvanceTypoExprCorrectionStreams() {
8453 for (auto TE : TypoExprs) {
8454 auto &State = SemaRef.getTypoExprState(TE);
8455 TransformCache.erase(TE);
8456 if (!State.Consumer->hasMadeAnyCorrectionProgress())
8457 return false;
8458 if (!State.Consumer->finished())
8459 return true;
8460 State.Consumer->resetCorrectionStream();
8461 }
8462 return false;
8463 }
8464
getDeclFromExpr(Expr * E)8465 NamedDecl *getDeclFromExpr(Expr *E) {
8466 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8467 E = OverloadResolution[OE];
8468
8469 if (!E)
8470 return nullptr;
8471 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8472 return DRE->getFoundDecl();
8473 if (auto *ME = dyn_cast<MemberExpr>(E))
8474 return ME->getFoundDecl();
8475 // FIXME: Add any other expr types that could be be seen by the delayed typo
8476 // correction TreeTransform for which the corresponding TypoCorrection could
8477 // contain multiple decls.
8478 return nullptr;
8479 }
8480
TryTransform(Expr * E)8481 ExprResult TryTransform(Expr *E) {
8482 Sema::SFINAETrap Trap(SemaRef);
8483 ExprResult Res = TransformExpr(E);
8484 if (Trap.hasErrorOccurred() || Res.isInvalid())
8485 return ExprError();
8486
8487 return ExprFilter(Res.get());
8488 }
8489
8490 // Since correcting typos may intoduce new TypoExprs, this function
8491 // checks for new TypoExprs and recurses if it finds any. Note that it will
8492 // only succeed if it is able to correct all typos in the given expression.
CheckForRecursiveTypos(ExprResult Res,bool & IsAmbiguous)8493 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8494 if (Res.isInvalid()) {
8495 return Res;
8496 }
8497 // Check to see if any new TypoExprs were created. If so, we need to recurse
8498 // to check their validity.
8499 Expr *FixedExpr = Res.get();
8500
8501 auto SavedTypoExprs = std::move(TypoExprs);
8502 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8503 TypoExprs.clear();
8504 AmbiguousTypoExprs.clear();
8505
8506 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8507 if (!TypoExprs.empty()) {
8508 // Recurse to handle newly created TypoExprs. If we're not able to
8509 // handle them, discard these TypoExprs.
8510 ExprResult RecurResult =
8511 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8512 if (RecurResult.isInvalid()) {
8513 Res = ExprError();
8514 // Recursive corrections didn't work, wipe them away and don't add
8515 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8516 // since we don't want to clear them twice. Note: it's possible the
8517 // TypoExprs were created recursively and thus won't be in our
8518 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8519 auto &SemaTypoExprs = SemaRef.TypoExprs;
8520 for (auto TE : TypoExprs) {
8521 TransformCache.erase(TE);
8522 SemaRef.clearDelayedTypo(TE);
8523
8524 auto SI = find(SemaTypoExprs, TE);
8525 if (SI != SemaTypoExprs.end()) {
8526 SemaTypoExprs.erase(SI);
8527 }
8528 }
8529 } else {
8530 // TypoExpr is valid: add newly created TypoExprs since we were
8531 // able to correct them.
8532 Res = RecurResult;
8533 SavedTypoExprs.set_union(TypoExprs);
8534 }
8535 }
8536
8537 TypoExprs = std::move(SavedTypoExprs);
8538 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8539
8540 return Res;
8541 }
8542
8543 // Try to transform the given expression, looping through the correction
8544 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8545 //
8546 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8547 // true and this method immediately will return an `ExprError`.
RecursiveTransformLoop(Expr * E,bool & IsAmbiguous)8548 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8549 ExprResult Res;
8550 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8551 SemaRef.TypoExprs.clear();
8552
8553 while (true) {
8554 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8555
8556 // Recursion encountered an ambiguous correction. This means that our
8557 // correction itself is ambiguous, so stop now.
8558 if (IsAmbiguous)
8559 break;
8560
8561 // If the transform is still valid after checking for any new typos,
8562 // it's good to go.
8563 if (!Res.isInvalid())
8564 break;
8565
8566 // The transform was invalid, see if we have any TypoExprs with untried
8567 // correction candidates.
8568 if (!CheckAndAdvanceTypoExprCorrectionStreams())
8569 break;
8570 }
8571
8572 // If we found a valid result, double check to make sure it's not ambiguous.
8573 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8574 auto SavedTransformCache =
8575 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8576
8577 // Ensure none of the TypoExprs have multiple typo correction candidates
8578 // with the same edit length that pass all the checks and filters.
8579 while (!AmbiguousTypoExprs.empty()) {
8580 auto TE = AmbiguousTypoExprs.back();
8581
8582 // TryTransform itself can create new Typos, adding them to the TypoExpr map
8583 // and invalidating our TypoExprState, so always fetch it instead of storing.
8584 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8585
8586 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8587 TypoCorrection Next;
8588 do {
8589 // Fetch the next correction by erasing the typo from the cache and calling
8590 // `TryTransform` which will iterate through corrections in
8591 // `TransformTypoExpr`.
8592 TransformCache.erase(TE);
8593 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8594
8595 if (!AmbigRes.isInvalid() || IsAmbiguous) {
8596 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8597 SavedTransformCache.erase(TE);
8598 Res = ExprError();
8599 IsAmbiguous = true;
8600 break;
8601 }
8602 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8603 Next.getEditDistance(false) == TC.getEditDistance(false));
8604
8605 if (IsAmbiguous)
8606 break;
8607
8608 AmbiguousTypoExprs.remove(TE);
8609 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8610 TransformCache[TE] = SavedTransformCache[TE];
8611 }
8612 TransformCache = std::move(SavedTransformCache);
8613 }
8614
8615 // Wipe away any newly created TypoExprs that we don't know about. Since we
8616 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8617 // possible if a `TypoExpr` is created during a transformation but then
8618 // fails before we can discover it.
8619 auto &SemaTypoExprs = SemaRef.TypoExprs;
8620 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8621 auto TE = *Iterator;
8622 auto FI = find(TypoExprs, TE);
8623 if (FI != TypoExprs.end()) {
8624 Iterator++;
8625 continue;
8626 }
8627 SemaRef.clearDelayedTypo(TE);
8628 Iterator = SemaTypoExprs.erase(Iterator);
8629 }
8630 SemaRef.TypoExprs = std::move(SavedTypoExprs);
8631
8632 return Res;
8633 }
8634
8635 public:
TransformTypos(Sema & SemaRef,VarDecl * InitDecl,llvm::function_ref<ExprResult (Expr *)> Filter)8636 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8637 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
8638
RebuildCallExpr(Expr * Callee,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig=nullptr)8639 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8640 MultiExprArg Args,
8641 SourceLocation RParenLoc,
8642 Expr *ExecConfig = nullptr) {
8643 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8644 RParenLoc, ExecConfig);
8645 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
8646 if (Result.isUsable()) {
8647 Expr *ResultCall = Result.get();
8648 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8649 ResultCall = BE->getSubExpr();
8650 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8651 OverloadResolution[OE] = CE->getCallee();
8652 }
8653 }
8654 return Result;
8655 }
8656
TransformLambdaExpr(LambdaExpr * E)8657 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8658
TransformBlockExpr(BlockExpr * E)8659 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8660
Transform(Expr * E)8661 ExprResult Transform(Expr *E) {
8662 bool IsAmbiguous = false;
8663 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
8664
8665 if (!Res.isUsable())
8666 FindTypoExprs(TypoExprs).TraverseStmt(E);
8667
8668 EmitAllDiagnostics(IsAmbiguous);
8669
8670 return Res;
8671 }
8672
TransformTypoExpr(TypoExpr * E)8673 ExprResult TransformTypoExpr(TypoExpr *E) {
8674 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8675 // cached transformation result if there is one and the TypoExpr isn't the
8676 // first one that was encountered.
8677 auto &CacheEntry = TransformCache[E];
8678 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8679 return CacheEntry;
8680 }
8681
8682 auto &State = SemaRef.getTypoExprState(E);
8683 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
8684
8685 // For the first TypoExpr and an uncached TypoExpr, find the next likely
8686 // typo correction and return it.
8687 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
8688 if (InitDecl && TC.getFoundDecl() == InitDecl)
8689 continue;
8690 // FIXME: If we would typo-correct to an invalid declaration, it's
8691 // probably best to just suppress all errors from this typo correction.
8692 ExprResult NE = State.RecoveryHandler ?
8693 State.RecoveryHandler(SemaRef, E, TC) :
8694 attemptRecovery(SemaRef, *State.Consumer, TC);
8695 if (!NE.isInvalid()) {
8696 // Check whether there may be a second viable correction with the same
8697 // edit distance; if so, remember this TypoExpr may have an ambiguous
8698 // correction so it can be more thoroughly vetted later.
8699 TypoCorrection Next;
8700 if ((Next = State.Consumer->peekNextCorrection()) &&
8701 Next.getEditDistance(false) == TC.getEditDistance(false)) {
8702 AmbiguousTypoExprs.insert(E);
8703 } else {
8704 AmbiguousTypoExprs.remove(E);
8705 }
8706 assert(!NE.isUnset() &&
8707 "Typo was transformed into a valid-but-null ExprResult");
8708 return CacheEntry = NE;
8709 }
8710 }
8711 return CacheEntry = ExprError();
8712 }
8713 };
8714 }
8715
8716 ExprResult
CorrectDelayedTyposInExpr(Expr * E,VarDecl * InitDecl,bool RecoverUncorrectedTypos,llvm::function_ref<ExprResult (Expr *)> Filter)8717 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
8718 bool RecoverUncorrectedTypos,
8719 llvm::function_ref<ExprResult(Expr *)> Filter) {
8720 // If the current evaluation context indicates there are uncorrected typos
8721 // and the current expression isn't guaranteed to not have typos, try to
8722 // resolve any TypoExpr nodes that might be in the expression.
8723 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
8724 (E->isTypeDependent() || E->isValueDependent() ||
8725 E->isInstantiationDependent())) {
8726 auto TyposResolved = DelayedTypos.size();
8727 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
8728 TyposResolved -= DelayedTypos.size();
8729 if (Result.isInvalid() || Result.get() != E) {
8730 ExprEvalContexts.back().NumTypos -= TyposResolved;
8731 if (Result.isInvalid() && RecoverUncorrectedTypos) {
8732 struct TyposReplace : TreeTransform<TyposReplace> {
8733 TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
8734 ExprResult TransformTypoExpr(clang::TypoExpr *E) {
8735 return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
8736 E->getEndLoc(), {});
8737 }
8738 } TT(*this);
8739 return TT.TransformExpr(E);
8740 }
8741 return Result;
8742 }
8743 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
8744 }
8745 return E;
8746 }
8747
ActOnFinishFullExpr(Expr * FE,SourceLocation CC,bool DiscardedValue,bool IsConstexpr)8748 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
8749 bool DiscardedValue,
8750 bool IsConstexpr) {
8751 ExprResult FullExpr = FE;
8752
8753 if (!FullExpr.get())
8754 return ExprError();
8755
8756 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
8757 return ExprError();
8758
8759 if (DiscardedValue) {
8760 // Top-level expressions default to 'id' when we're in a debugger.
8761 if (getLangOpts().DebuggerCastResultToId &&
8762 FullExpr.get()->getType() == Context.UnknownAnyTy) {
8763 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
8764 if (FullExpr.isInvalid())
8765 return ExprError();
8766 }
8767
8768 FullExpr = CheckPlaceholderExpr(FullExpr.get());
8769 if (FullExpr.isInvalid())
8770 return ExprError();
8771
8772 FullExpr = IgnoredValueConversions(FullExpr.get());
8773 if (FullExpr.isInvalid())
8774 return ExprError();
8775
8776 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
8777 }
8778
8779 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
8780 /*RecoverUncorrectedTypos=*/true);
8781 if (FullExpr.isInvalid())
8782 return ExprError();
8783
8784 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
8785
8786 // At the end of this full expression (which could be a deeply nested
8787 // lambda), if there is a potential capture within the nested lambda,
8788 // have the outer capture-able lambda try and capture it.
8789 // Consider the following code:
8790 // void f(int, int);
8791 // void f(const int&, double);
8792 // void foo() {
8793 // const int x = 10, y = 20;
8794 // auto L = [=](auto a) {
8795 // auto M = [=](auto b) {
8796 // f(x, b); <-- requires x to be captured by L and M
8797 // f(y, a); <-- requires y to be captured by L, but not all Ms
8798 // };
8799 // };
8800 // }
8801
8802 // FIXME: Also consider what happens for something like this that involves
8803 // the gnu-extension statement-expressions or even lambda-init-captures:
8804 // void f() {
8805 // const int n = 0;
8806 // auto L = [&](auto a) {
8807 // +n + ({ 0; a; });
8808 // };
8809 // }
8810 //
8811 // Here, we see +n, and then the full-expression 0; ends, so we don't
8812 // capture n (and instead remove it from our list of potential captures),
8813 // and then the full-expression +n + ({ 0; }); ends, but it's too late
8814 // for us to see that we need to capture n after all.
8815
8816 LambdaScopeInfo *const CurrentLSI =
8817 getCurLambda(/*IgnoreCapturedRegions=*/true);
8818 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
8819 // even if CurContext is not a lambda call operator. Refer to that Bug Report
8820 // for an example of the code that might cause this asynchrony.
8821 // By ensuring we are in the context of a lambda's call operator
8822 // we can fix the bug (we only need to check whether we need to capture
8823 // if we are within a lambda's body); but per the comments in that
8824 // PR, a proper fix would entail :
8825 // "Alternative suggestion:
8826 // - Add to Sema an integer holding the smallest (outermost) scope
8827 // index that we are *lexically* within, and save/restore/set to
8828 // FunctionScopes.size() in InstantiatingTemplate's
8829 // constructor/destructor.
8830 // - Teach the handful of places that iterate over FunctionScopes to
8831 // stop at the outermost enclosing lexical scope."
8832 DeclContext *DC = CurContext;
8833 while (DC && isa<CapturedDecl>(DC))
8834 DC = DC->getParent();
8835 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
8836 if (IsInLambdaDeclContext && CurrentLSI &&
8837 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
8838 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
8839 *this);
8840 return MaybeCreateExprWithCleanups(FullExpr);
8841 }
8842
ActOnFinishFullStmt(Stmt * FullStmt)8843 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
8844 if (!FullStmt) return StmtError();
8845
8846 return MaybeCreateStmtWithCleanups(FullStmt);
8847 }
8848
8849 Sema::IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope * S,CXXScopeSpec & SS,const DeclarationNameInfo & TargetNameInfo)8850 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
8851 CXXScopeSpec &SS,
8852 const DeclarationNameInfo &TargetNameInfo) {
8853 DeclarationName TargetName = TargetNameInfo.getName();
8854 if (!TargetName)
8855 return IER_DoesNotExist;
8856
8857 // If the name itself is dependent, then the result is dependent.
8858 if (TargetName.isDependentName())
8859 return IER_Dependent;
8860
8861 // Do the redeclaration lookup in the current scope.
8862 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
8863 Sema::NotForRedeclaration);
8864 LookupParsedName(R, S, &SS);
8865 R.suppressDiagnostics();
8866
8867 switch (R.getResultKind()) {
8868 case LookupResult::Found:
8869 case LookupResult::FoundOverloaded:
8870 case LookupResult::FoundUnresolvedValue:
8871 case LookupResult::Ambiguous:
8872 return IER_Exists;
8873
8874 case LookupResult::NotFound:
8875 return IER_DoesNotExist;
8876
8877 case LookupResult::NotFoundInCurrentInstantiation:
8878 return IER_Dependent;
8879 }
8880
8881 llvm_unreachable("Invalid LookupResult Kind!");
8882 }
8883
8884 Sema::IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope * S,SourceLocation KeywordLoc,bool IsIfExists,CXXScopeSpec & SS,UnqualifiedId & Name)8885 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
8886 bool IsIfExists, CXXScopeSpec &SS,
8887 UnqualifiedId &Name) {
8888 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8889
8890 // Check for an unexpanded parameter pack.
8891 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
8892 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
8893 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
8894 return IER_Error;
8895
8896 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
8897 }
8898
ActOnSimpleRequirement(Expr * E)8899 concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {
8900 return BuildExprRequirement(E, /*IsSimple=*/true,
8901 /*NoexceptLoc=*/SourceLocation(),
8902 /*ReturnTypeRequirement=*/{});
8903 }
8904
8905 concepts::Requirement *
ActOnTypeRequirement(SourceLocation TypenameKWLoc,CXXScopeSpec & SS,SourceLocation NameLoc,IdentifierInfo * TypeName,TemplateIdAnnotation * TemplateId)8906 Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS,
8907 SourceLocation NameLoc, IdentifierInfo *TypeName,
8908 TemplateIdAnnotation *TemplateId) {
8909 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
8910 "Exactly one of TypeName and TemplateId must be specified.");
8911 TypeSourceInfo *TSI = nullptr;
8912 if (TypeName) {
8913 QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc,
8914 SS.getWithLocInContext(Context), *TypeName,
8915 NameLoc, &TSI, /*DeducedTSTContext=*/false);
8916 if (T.isNull())
8917 return nullptr;
8918 } else {
8919 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
8920 TemplateId->NumArgs);
8921 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
8922 TemplateId->TemplateKWLoc,
8923 TemplateId->Template, TemplateId->Name,
8924 TemplateId->TemplateNameLoc,
8925 TemplateId->LAngleLoc, ArgsPtr,
8926 TemplateId->RAngleLoc);
8927 if (T.isInvalid())
8928 return nullptr;
8929 if (GetTypeFromParser(T.get(), &TSI).isNull())
8930 return nullptr;
8931 }
8932 return BuildTypeRequirement(TSI);
8933 }
8934
8935 concepts::Requirement *
ActOnCompoundRequirement(Expr * E,SourceLocation NoexceptLoc)8936 Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {
8937 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
8938 /*ReturnTypeRequirement=*/{});
8939 }
8940
8941 concepts::Requirement *
ActOnCompoundRequirement(Expr * E,SourceLocation NoexceptLoc,CXXScopeSpec & SS,TemplateIdAnnotation * TypeConstraint,unsigned Depth)8942 Sema::ActOnCompoundRequirement(
8943 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8944 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
8945 // C++2a [expr.prim.req.compound] p1.3.3
8946 // [..] the expression is deduced against an invented function template
8947 // F [...] F is a void function template with a single type template
8948 // parameter T declared with the constrained-parameter. Form a new
8949 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
8950 // around the constrained-parameter. F has a single parameter whose
8951 // type-specifier is cv T followed by the abstract-declarator. [...]
8952 //
8953 // The cv part is done in the calling function - we get the concept with
8954 // arguments and the abstract declarator with the correct CV qualification and
8955 // have to synthesize T and the single parameter of F.
8956 auto &II = Context.Idents.get("expr-type");
8957 auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,
8958 SourceLocation(),
8959 SourceLocation(), Depth,
8960 /*Index=*/0, &II,
8961 /*Typename=*/true,
8962 /*ParameterPack=*/false,
8963 /*HasTypeConstraint=*/true);
8964
8965 if (BuildTypeConstraint(SS, TypeConstraint, TParam,
8966 /*EllipsisLoc=*/SourceLocation(),
8967 /*AllowUnexpandedPack=*/true))
8968 // Just produce a requirement with no type requirements.
8969 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
8970
8971 auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),
8972 SourceLocation(),
8973 ArrayRef<NamedDecl *>(TParam),
8974 SourceLocation(),
8975 /*RequiresClause=*/nullptr);
8976 return BuildExprRequirement(
8977 E, /*IsSimple=*/false, NoexceptLoc,
8978 concepts::ExprRequirement::ReturnTypeRequirement(TPL));
8979 }
8980
8981 concepts::ExprRequirement *
BuildExprRequirement(Expr * E,bool IsSimple,SourceLocation NoexceptLoc,concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement)8982 Sema::BuildExprRequirement(
8983 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
8984 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8985 auto Status = concepts::ExprRequirement::SS_Satisfied;
8986 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
8987 if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent())
8988 Status = concepts::ExprRequirement::SS_Dependent;
8989 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
8990 Status = concepts::ExprRequirement::SS_NoexceptNotMet;
8991 else if (ReturnTypeRequirement.isSubstitutionFailure())
8992 Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;
8993 else if (ReturnTypeRequirement.isTypeConstraint()) {
8994 // C++2a [expr.prim.req]p1.3.3
8995 // The immediately-declared constraint ([temp]) of decltype((E)) shall
8996 // be satisfied.
8997 TemplateParameterList *TPL =
8998 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
8999 QualType MatchedType =
9000 Context.getReferenceQualifiedType(E).getCanonicalType();
9001 llvm::SmallVector<TemplateArgument, 1> Args;
9002 Args.push_back(TemplateArgument(MatchedType));
9003 TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args);
9004 MultiLevelTemplateArgumentList MLTAL(TAL);
9005 for (unsigned I = 0; I < TPL->getDepth(); ++I)
9006 MLTAL.addOuterRetainedLevel();
9007 Expr *IDC =
9008 cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint()
9009 ->getImmediatelyDeclaredConstraint();
9010 ExprResult Constraint = SubstExpr(IDC, MLTAL);
9011 if (Constraint.isInvalid()) {
9012 Status = concepts::ExprRequirement::SS_ExprSubstitutionFailure;
9013 } else {
9014 SubstitutedConstraintExpr =
9015 cast<ConceptSpecializationExpr>(Constraint.get());
9016 if (!SubstitutedConstraintExpr->isSatisfied())
9017 Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
9018 }
9019 }
9020 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
9021 ReturnTypeRequirement, Status,
9022 SubstitutedConstraintExpr);
9023 }
9024
9025 concepts::ExprRequirement *
BuildExprRequirement(concepts::Requirement::SubstitutionDiagnostic * ExprSubstitutionDiagnostic,bool IsSimple,SourceLocation NoexceptLoc,concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement)9026 Sema::BuildExprRequirement(
9027 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
9028 bool IsSimple, SourceLocation NoexceptLoc,
9029 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
9030 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
9031 IsSimple, NoexceptLoc,
9032 ReturnTypeRequirement);
9033 }
9034
9035 concepts::TypeRequirement *
BuildTypeRequirement(TypeSourceInfo * Type)9036 Sema::BuildTypeRequirement(TypeSourceInfo *Type) {
9037 return new (Context) concepts::TypeRequirement(Type);
9038 }
9039
9040 concepts::TypeRequirement *
BuildTypeRequirement(concepts::Requirement::SubstitutionDiagnostic * SubstDiag)9041 Sema::BuildTypeRequirement(
9042 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
9043 return new (Context) concepts::TypeRequirement(SubstDiag);
9044 }
9045
ActOnNestedRequirement(Expr * Constraint)9046 concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {
9047 return BuildNestedRequirement(Constraint);
9048 }
9049
9050 concepts::NestedRequirement *
BuildNestedRequirement(Expr * Constraint)9051 Sema::BuildNestedRequirement(Expr *Constraint) {
9052 ConstraintSatisfaction Satisfaction;
9053 if (!Constraint->isInstantiationDependent() &&
9054 CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
9055 Constraint->getSourceRange(), Satisfaction))
9056 return nullptr;
9057 return new (Context) concepts::NestedRequirement(Context, Constraint,
9058 Satisfaction);
9059 }
9060
9061 concepts::NestedRequirement *
BuildNestedRequirement(concepts::Requirement::SubstitutionDiagnostic * SubstDiag)9062 Sema::BuildNestedRequirement(
9063 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
9064 return new (Context) concepts::NestedRequirement(SubstDiag);
9065 }
9066
9067 RequiresExprBodyDecl *
ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,ArrayRef<ParmVarDecl * > LocalParameters,Scope * BodyScope)9068 Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
9069 ArrayRef<ParmVarDecl *> LocalParameters,
9070 Scope *BodyScope) {
9071 assert(BodyScope);
9072
9073 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,
9074 RequiresKWLoc);
9075
9076 PushDeclContext(BodyScope, Body);
9077
9078 for (ParmVarDecl *Param : LocalParameters) {
9079 if (Param->hasDefaultArg())
9080 // C++2a [expr.prim.req] p4
9081 // [...] A local parameter of a requires-expression shall not have a
9082 // default argument. [...]
9083 Diag(Param->getDefaultArgRange().getBegin(),
9084 diag::err_requires_expr_local_parameter_default_argument);
9085 // Ignore default argument and move on
9086
9087 Param->setDeclContext(Body);
9088 // If this has an identifier, add it to the scope stack.
9089 if (Param->getIdentifier()) {
9090 CheckShadow(BodyScope, Param);
9091 PushOnScopeChains(Param, BodyScope);
9092 }
9093 }
9094 return Body;
9095 }
9096
ActOnFinishRequiresExpr()9097 void Sema::ActOnFinishRequiresExpr() {
9098 assert(CurContext && "DeclContext imbalance!");
9099 CurContext = CurContext->getLexicalParent();
9100 assert(CurContext && "Popped translation unit!");
9101 }
9102
9103 ExprResult
ActOnRequiresExpr(SourceLocation RequiresKWLoc,RequiresExprBodyDecl * Body,ArrayRef<ParmVarDecl * > LocalParameters,ArrayRef<concepts::Requirement * > Requirements,SourceLocation ClosingBraceLoc)9104 Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc,
9105 RequiresExprBodyDecl *Body,
9106 ArrayRef<ParmVarDecl *> LocalParameters,
9107 ArrayRef<concepts::Requirement *> Requirements,
9108 SourceLocation ClosingBraceLoc) {
9109 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters,
9110 Requirements, ClosingBraceLoc);
9111 if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE))
9112 return ExprError();
9113 return RE;
9114 }
9115