1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Implements semantic analysis for C++ expressions.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Sema/SemaInternal.h"
16 #include "TypeLocBuilder.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/ParsedTemplate.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/SemaLambda.h"
36 #include "clang/Sema/TemplateDeduction.h"
37 #include "llvm/ADT/APInt.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/Support/ErrorHandling.h"
40 using namespace clang;
43 /// \brief Handle the result of the special case name lookup for inheriting
44 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
45 /// constructor names in member using declarations, even if 'X' is not the
46 /// name of the corresponding type.
47 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
48 SourceLocation NameLoc,
49 IdentifierInfo &Name) {
50 NestedNameSpecifier *NNS = SS.getScopeRep();
52 // Convert the nested-name-specifier into a type.
54 switch (NNS->getKind()) {
55 case NestedNameSpecifier::TypeSpec:
56 case NestedNameSpecifier::TypeSpecWithTemplate:
57 Type = QualType(NNS->getAsType(), 0);
60 case NestedNameSpecifier::Identifier:
61 // Strip off the last layer of the nested-name-specifier and build a
62 // typename type for it.
63 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
64 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
65 NNS->getAsIdentifier());
68 case NestedNameSpecifier::Global:
69 case NestedNameSpecifier::Namespace:
70 case NestedNameSpecifier::NamespaceAlias:
71 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74 // This reference to the type is located entirely at the location of the
75 // final identifier in the qualified-id.
76 return CreateParsedType(Type,
77 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
82 SourceLocation NameLoc,
83 Scope *S, CXXScopeSpec &SS,
84 ParsedType ObjectTypePtr,
85 bool EnteringContext) {
86 // Determine where to perform name lookup.
88 // FIXME: This area of the standard is very messy, and the current
89 // wording is rather unclear about which scopes we search for the
90 // destructor name; see core issues 399 and 555. Issue 399 in
91 // particular shows where the current description of destructor name
92 // lookup is completely out of line with existing practice, e.g.,
93 // this appears to be ill-formed:
96 // template <typename T> struct S {
101 // void f(N::S<int>* s) {
102 // s->N::S<int>::~S();
105 // See also PR6358 and PR6359.
106 // For this reason, we're currently only doing the C++03 version of this
107 // code; the C++0x version has to wait until we get a proper spec.
109 DeclContext *LookupCtx = 0;
110 bool isDependent = false;
111 bool LookInScope = false;
113 // If we have an object type, it's because we are in a
114 // pseudo-destructor-expression or a member access expression, and
115 // we know what type we're looking for.
117 SearchType = GetTypeFromParser(ObjectTypePtr);
120 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
122 bool AlreadySearched = false;
123 bool LookAtPrefix = true;
124 // C++ [basic.lookup.qual]p6:
125 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
126 // the type-names are looked up as types in the scope designated by the
127 // nested-name-specifier. In a qualified-id of the form:
129 // ::[opt] nested-name-specifier ~ class-name
131 // where the nested-name-specifier designates a namespace scope, and in
132 // a qualified-id of the form:
134 // ::opt nested-name-specifier class-name :: ~ class-name
136 // the class-names are looked up as types in the scope designated by
137 // the nested-name-specifier.
139 // Here, we check the first case (completely) and determine whether the
140 // code below is permitted to look at the prefix of the
141 // nested-name-specifier.
142 DeclContext *DC = computeDeclContext(SS, EnteringContext);
143 if (DC && DC->isFileContext()) {
144 AlreadySearched = true;
147 } else if (DC && isa<CXXRecordDecl>(DC))
148 LookAtPrefix = false;
150 // The second case from the C++03 rules quoted further above.
151 NestedNameSpecifier *Prefix = 0;
152 if (AlreadySearched) {
153 // Nothing left to do.
154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155 CXXScopeSpec PrefixSS;
156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158 isDependent = isDependentScopeSpecifier(PrefixSS);
159 } else if (ObjectTypePtr) {
160 LookupCtx = computeDeclContext(SearchType);
161 isDependent = SearchType->isDependentType();
163 LookupCtx = computeDeclContext(SS, EnteringContext);
164 isDependent = LookupCtx && LookupCtx->isDependentContext();
168 } else if (ObjectTypePtr) {
169 // C++ [basic.lookup.classref]p3:
170 // If the unqualified-id is ~type-name, the type-name is looked up
171 // in the context of the entire postfix-expression. If the type T
172 // of the object expression is of a class type C, the type-name is
173 // also looked up in the scope of class C. At least one of the
174 // lookups shall find a name that refers to (possibly
176 LookupCtx = computeDeclContext(SearchType);
177 isDependent = SearchType->isDependentType();
178 assert((isDependent || !SearchType->isIncompleteType()) &&
179 "Caller should have completed object type");
183 // Perform lookup into the current scope (only).
187 TypeDecl *NonMatchingTypeDecl = 0;
188 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
189 for (unsigned Step = 0; Step != 2; ++Step) {
190 // Look for the name first in the computed lookup context (if we
191 // have one) and, if that fails to find a match, in the scope (if
192 // we're allowed to look there).
194 if (Step == 0 && LookupCtx)
195 LookupQualifiedName(Found, LookupCtx);
196 else if (Step == 1 && LookInScope && S)
197 LookupName(Found, S);
201 // FIXME: Should we be suppressing ambiguities here?
202 if (Found.isAmbiguous())
205 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
206 QualType T = Context.getTypeDeclType(Type);
208 if (SearchType.isNull() || SearchType->isDependentType() ||
209 Context.hasSameUnqualifiedType(T, SearchType)) {
210 // We found our type!
212 return ParsedType::make(T);
215 if (!SearchType.isNull())
216 NonMatchingTypeDecl = Type;
219 // If the name that we found is a class template name, and it is
220 // the same name as the template name in the last part of the
221 // nested-name-specifier (if present) or the object type, then
222 // this is the destructor for that class.
223 // FIXME: This is a workaround until we get real drafting for core
224 // issue 399, for which there isn't even an obvious direction.
225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226 QualType MemberOfType;
228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229 // Figure out the type of the context, if it has one.
230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231 MemberOfType = Context.getTypeDeclType(Record);
234 if (MemberOfType.isNull())
235 MemberOfType = SearchType;
237 if (MemberOfType.isNull())
240 // We're referring into a class template specialization. If the
241 // class template we found is the same as the template being
242 // specialized, we found what we are looking for.
243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244 if (ClassTemplateSpecializationDecl *Spec
245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247 Template->getCanonicalDecl())
248 return ParsedType::make(MemberOfType);
254 // We're referring to an unresolved class template
255 // specialization. Determine whether we class template we found
256 // is the same as the template being specialized or, if we don't
257 // know which template is being specialized, that it at least
258 // has the same name.
259 if (const TemplateSpecializationType *SpecType
260 = MemberOfType->getAs<TemplateSpecializationType>()) {
261 TemplateName SpecName = SpecType->getTemplateName();
263 // The class template we found is the same template being
265 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
266 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
267 return ParsedType::make(MemberOfType);
272 // The class template we found has the same name as the
273 // (dependent) template name being specialized.
274 if (DependentTemplateName *DepTemplate
275 = SpecName.getAsDependentTemplateName()) {
276 if (DepTemplate->isIdentifier() &&
277 DepTemplate->getIdentifier() == Template->getIdentifier())
278 return ParsedType::make(MemberOfType);
287 // We didn't find our type, but that's okay: it's dependent
290 // FIXME: What if we have no nested-name-specifier?
291 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
292 SS.getWithLocInContext(Context),
294 return ParsedType::make(T);
297 if (NonMatchingTypeDecl) {
298 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
299 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
301 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
303 } else if (ObjectTypePtr)
304 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
307 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
308 diag::err_destructor_class_name);
310 const DeclContext *Ctx = S->getEntity();
311 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
312 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
313 Class->getNameAsString());
320 ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
321 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
323 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
324 && "only get destructor types from declspecs");
325 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
326 QualType SearchType = GetTypeFromParser(ObjectType);
327 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
328 return ParsedType::make(T);
331 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
336 /// \brief Build a C++ typeid expression with a type operand.
337 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
338 SourceLocation TypeidLoc,
339 TypeSourceInfo *Operand,
340 SourceLocation RParenLoc) {
341 // C++ [expr.typeid]p4:
342 // The top-level cv-qualifiers of the lvalue expression or the type-id
343 // that is the operand of typeid are always ignored.
344 // If the type of the type-id is a class type or a reference to a class
345 // type, the class shall be completely-defined.
348 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
350 if (T->getAs<RecordType>() &&
351 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
354 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
356 SourceRange(TypeidLoc, RParenLoc)));
359 /// \brief Build a C++ typeid expression with an expression operand.
360 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
361 SourceLocation TypeidLoc,
363 SourceLocation RParenLoc) {
364 if (E && !E->isTypeDependent()) {
365 if (E->getType()->isPlaceholderType()) {
366 ExprResult result = CheckPlaceholderExpr(E);
367 if (result.isInvalid()) return ExprError();
371 QualType T = E->getType();
372 if (const RecordType *RecordT = T->getAs<RecordType>()) {
373 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
374 // C++ [expr.typeid]p3:
375 // [...] If the type of the expression is a class type, the class
376 // shall be completely-defined.
377 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
380 // C++ [expr.typeid]p3:
381 // When typeid is applied to an expression other than an glvalue of a
382 // polymorphic class type [...] [the] expression is an unevaluated
384 if (RecordD->isPolymorphic() && E->isGLValue()) {
385 // The subexpression is potentially evaluated; switch the context
386 // and recheck the subexpression.
387 ExprResult Result = TransformToPotentiallyEvaluated(E);
388 if (Result.isInvalid()) return ExprError();
391 // We require a vtable to query the type at run time.
392 MarkVTableUsed(TypeidLoc, RecordD);
396 // C++ [expr.typeid]p4:
397 // [...] If the type of the type-id is a reference to a possibly
398 // cv-qualified type, the result of the typeid expression refers to a
399 // std::type_info object representing the cv-unqualified referenced
402 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
403 if (!Context.hasSameType(T, UnqualT)) {
405 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
409 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
411 SourceRange(TypeidLoc, RParenLoc)));
414 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
416 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
417 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
418 // Find the std::type_info type.
419 if (!getStdNamespace())
420 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
422 if (!CXXTypeInfoDecl) {
423 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
424 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
425 LookupQualifiedName(R, getStdNamespace());
426 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
427 // Microsoft's typeinfo doesn't have type_info in std but in the global
428 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
429 if (!CXXTypeInfoDecl && LangOpts.MicrosoftMode) {
430 LookupQualifiedName(R, Context.getTranslationUnitDecl());
431 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
433 if (!CXXTypeInfoDecl)
434 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
437 if (!getLangOpts().RTTI) {
438 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
441 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
444 // The operand is a type; handle it as such.
445 TypeSourceInfo *TInfo = 0;
446 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
452 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
454 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
457 // The operand is an expression.
458 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
461 /// \brief Build a Microsoft __uuidof expression with a type operand.
462 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
463 SourceLocation TypeidLoc,
464 TypeSourceInfo *Operand,
465 SourceLocation RParenLoc) {
466 if (!Operand->getType()->isDependentType()) {
467 bool HasMultipleGUIDs = false;
468 if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType(),
469 &HasMultipleGUIDs)) {
470 if (HasMultipleGUIDs)
471 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
473 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
477 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
479 SourceRange(TypeidLoc, RParenLoc)));
482 /// \brief Build a Microsoft __uuidof expression with an expression operand.
483 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
484 SourceLocation TypeidLoc,
486 SourceLocation RParenLoc) {
487 if (!E->getType()->isDependentType()) {
488 bool HasMultipleGUIDs = false;
489 if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType(), &HasMultipleGUIDs) &&
490 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
491 if (HasMultipleGUIDs)
492 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
494 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
498 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
500 SourceRange(TypeidLoc, RParenLoc)));
503 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
505 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
506 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
507 // If MSVCGuidDecl has not been cached, do the lookup.
509 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
510 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
511 LookupQualifiedName(R, Context.getTranslationUnitDecl());
512 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
514 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
517 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
520 // The operand is a type; handle it as such.
521 TypeSourceInfo *TInfo = 0;
522 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
528 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
530 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
533 // The operand is an expression.
534 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
537 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
539 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
540 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
541 "Unknown C++ Boolean value!");
542 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
543 Context.BoolTy, OpLoc));
546 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
548 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
549 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
552 /// ActOnCXXThrow - Parse throw expressions.
554 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
555 bool IsThrownVarInScope = false;
557 // C++0x [class.copymove]p31:
558 // When certain criteria are met, an implementation is allowed to omit the
559 // copy/move construction of a class object [...]
561 // - in a throw-expression, when the operand is the name of a
562 // non-volatile automatic object (other than a function or catch-
563 // clause parameter) whose scope does not extend beyond the end of the
564 // innermost enclosing try-block (if there is one), the copy/move
565 // operation from the operand to the exception object (15.1) can be
566 // omitted by constructing the automatic object directly into the
568 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
569 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
570 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
571 for( ; S; S = S->getParent()) {
572 if (S->isDeclScope(Var)) {
573 IsThrownVarInScope = true;
578 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
579 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
587 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
590 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
591 bool IsThrownVarInScope) {
592 // Don't report an error if 'throw' is used in system headers.
593 if (!getLangOpts().CXXExceptions &&
594 !getSourceManager().isInSystemHeader(OpLoc))
595 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
597 if (Ex && !Ex->isTypeDependent()) {
598 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
599 if (ExRes.isInvalid())
604 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
605 IsThrownVarInScope));
608 /// CheckCXXThrowOperand - Validate the operand of a throw.
609 ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
610 bool IsThrownVarInScope) {
611 // C++ [except.throw]p3:
612 // A throw-expression initializes a temporary object, called the exception
613 // object, the type of which is determined by removing any top-level
614 // cv-qualifiers from the static type of the operand of throw and adjusting
615 // the type from "array of T" or "function returning T" to "pointer to T"
616 // or "pointer to function returning T", [...]
617 if (E->getType().hasQualifiers())
618 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
619 E->getValueKind()).take();
621 ExprResult Res = DefaultFunctionArrayConversion(E);
626 // If the type of the exception would be an incomplete type or a pointer
627 // to an incomplete type other than (cv) void the program is ill-formed.
628 QualType Ty = E->getType();
629 bool isPointer = false;
630 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
631 Ty = Ptr->getPointeeType();
634 if (!isPointer || !Ty->isVoidType()) {
635 if (RequireCompleteType(ThrowLoc, Ty,
636 isPointer? diag::err_throw_incomplete_ptr
637 : diag::err_throw_incomplete,
638 E->getSourceRange()))
641 if (RequireNonAbstractType(ThrowLoc, E->getType(),
642 diag::err_throw_abstract_type, E))
646 // Initialize the exception result. This implicitly weeds out
647 // abstract types or types with inaccessible copy constructors.
649 // C++0x [class.copymove]p31:
650 // When certain criteria are met, an implementation is allowed to omit the
651 // copy/move construction of a class object [...]
653 // - in a throw-expression, when the operand is the name of a
654 // non-volatile automatic object (other than a function or catch-clause
655 // parameter) whose scope does not extend beyond the end of the
656 // innermost enclosing try-block (if there is one), the copy/move
657 // operation from the operand to the exception object (15.1) can be
658 // omitted by constructing the automatic object directly into the
660 const VarDecl *NRVOVariable = 0;
661 if (IsThrownVarInScope)
662 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
664 InitializedEntity Entity =
665 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
666 /*NRVO=*/NRVOVariable != 0);
667 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
674 // If the exception has class type, we need additional handling.
675 const RecordType *RecordTy = Ty->getAs<RecordType>();
678 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
680 // If we are throwing a polymorphic class type or pointer thereof,
681 // exception handling will make use of the vtable.
682 MarkVTableUsed(ThrowLoc, RD);
684 // If a pointer is thrown, the referenced object will not be destroyed.
688 // If the class has a destructor, we must be able to call it.
689 if (RD->hasIrrelevantDestructor())
692 CXXDestructorDecl *Destructor = LookupDestructor(RD);
696 MarkFunctionReferenced(E->getExprLoc(), Destructor);
697 CheckDestructorAccess(E->getExprLoc(), Destructor,
698 PDiag(diag::err_access_dtor_exception) << Ty);
699 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
704 QualType Sema::getCurrentThisType() {
705 DeclContext *DC = getFunctionLevelDeclContext();
706 QualType ThisTy = CXXThisTypeOverride;
707 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
708 if (method && method->isInstance())
709 ThisTy = method->getThisType(Context);
715 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
717 unsigned CXXThisTypeQuals,
719 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
721 if (!Enabled || !ContextDecl)
724 CXXRecordDecl *Record = 0;
725 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
726 Record = Template->getTemplatedDecl();
728 Record = cast<CXXRecordDecl>(ContextDecl);
730 S.CXXThisTypeOverride
731 = S.Context.getPointerType(
732 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
734 this->Enabled = true;
738 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
740 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
744 static Expr *captureThis(ASTContext &Context, RecordDecl *RD,
745 QualType ThisTy, SourceLocation Loc) {
747 = FieldDecl::Create(Context, RD, Loc, Loc, 0, ThisTy,
748 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
749 0, false, ICIS_NoInit);
750 Field->setImplicit(true);
751 Field->setAccess(AS_private);
753 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/true);
756 bool Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit,
757 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt) {
758 // We don't need to capture this in an unevaluated context.
759 if (isUnevaluatedContext() && !Explicit)
762 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
763 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
764 // Otherwise, check that we can capture 'this'.
765 unsigned NumClosures = 0;
766 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
767 if (CapturingScopeInfo *CSI =
768 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
769 if (CSI->CXXThisCaptureIndex != 0) {
770 // 'this' is already being captured; there isn't anything more to do.
773 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
774 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
775 // This context can't implicitly capture 'this'; fail out.
776 if (BuildAndDiagnose)
777 Diag(Loc, diag::err_this_capture) << Explicit;
780 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
781 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
782 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
783 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
785 // This closure can capture 'this'; continue looking upwards.
790 // This context can't implicitly capture 'this'; fail out.
791 if (BuildAndDiagnose)
792 Diag(Loc, diag::err_this_capture) << Explicit;
797 if (!BuildAndDiagnose) return false;
798 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
799 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
801 for (unsigned idx = MaxFunctionScopesIndex; NumClosures;
802 --idx, --NumClosures) {
803 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
805 QualType ThisTy = getCurrentThisType();
806 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI))
807 // For lambda expressions, build a field and an initializing expression.
808 ThisExpr = captureThis(Context, LSI->Lambda, ThisTy, Loc);
809 else if (CapturedRegionScopeInfo *RSI
810 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
811 ThisExpr = captureThis(Context, RSI->TheRecordDecl, ThisTy, Loc);
813 bool isNested = NumClosures > 1;
814 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
819 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
820 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
821 /// is a non-lvalue expression whose value is the address of the object for
822 /// which the function is called.
824 QualType ThisTy = getCurrentThisType();
825 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
827 CheckCXXThisCapture(Loc);
828 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
831 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
832 // If we're outside the body of a member function, then we'll have a specified
834 if (CXXThisTypeOverride.isNull())
837 // Determine whether we're looking into a class that's currently being
839 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
840 return Class && Class->isBeingDefined();
844 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
845 SourceLocation LParenLoc,
847 SourceLocation RParenLoc) {
851 TypeSourceInfo *TInfo;
852 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
854 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
856 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
859 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
860 /// Can be interpreted either as function-style casting ("int(x)")
861 /// or class type construction ("ClassType(x,y,z)")
862 /// or creation of a value-initialized type ("int()").
864 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
865 SourceLocation LParenLoc,
867 SourceLocation RParenLoc) {
868 QualType Ty = TInfo->getType();
869 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
871 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
872 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
878 bool ListInitialization = LParenLoc.isInvalid();
879 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
880 && "List initialization must have initializer list as expression.");
881 SourceRange FullRange = SourceRange(TyBeginLoc,
882 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
884 // C++ [expr.type.conv]p1:
885 // If the expression list is a single expression, the type conversion
886 // expression is equivalent (in definedness, and if defined in meaning) to the
887 // corresponding cast expression.
888 if (Exprs.size() == 1 && !ListInitialization) {
889 Expr *Arg = Exprs[0];
890 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
893 QualType ElemTy = Ty;
894 if (Ty->isArrayType()) {
895 if (!ListInitialization)
896 return ExprError(Diag(TyBeginLoc,
897 diag::err_value_init_for_array_type) << FullRange);
898 ElemTy = Context.getBaseElementType(Ty);
901 if (!Ty->isVoidType() &&
902 RequireCompleteType(TyBeginLoc, ElemTy,
903 diag::err_invalid_incomplete_type_use, FullRange))
906 if (RequireNonAbstractType(TyBeginLoc, Ty,
907 diag::err_allocation_of_abstract_type))
910 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
911 InitializationKind Kind =
912 Exprs.size() ? ListInitialization
913 ? InitializationKind::CreateDirectList(TyBeginLoc)
914 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
915 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
916 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
917 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
919 if (Result.isInvalid() || !ListInitialization)
922 Expr *Inner = Result.get();
923 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
924 Inner = BTE->getSubExpr();
925 if (isa<InitListExpr>(Inner)) {
926 // If the list-initialization doesn't involve a constructor call, we'll get
927 // the initializer-list (with corrected type) back, but that's not what we
928 // want, since it will be treated as an initializer list in further
929 // processing. Explicitly insert a cast here.
930 QualType ResultType = Result.get()->getType();
931 Result = Owned(CXXFunctionalCastExpr::Create(
932 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
933 CK_NoOp, Result.take(), /*Path=*/ 0, LParenLoc, RParenLoc));
936 // FIXME: Improve AST representation?
940 /// doesUsualArrayDeleteWantSize - Answers whether the usual
941 /// operator delete[] for the given type has a size_t parameter.
942 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
943 QualType allocType) {
944 const RecordType *record =
945 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
946 if (!record) return false;
948 // Try to find an operator delete[] in class scope.
950 DeclarationName deleteName =
951 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
952 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
953 S.LookupQualifiedName(ops, record->getDecl());
955 // We're just doing this for information.
956 ops.suppressDiagnostics();
958 // Very likely: there's no operator delete[].
959 if (ops.empty()) return false;
961 // If it's ambiguous, it should be illegal to call operator delete[]
962 // on this thing, so it doesn't matter if we allocate extra space or not.
963 if (ops.isAmbiguous()) return false;
965 LookupResult::Filter filter = ops.makeFilter();
966 while (filter.hasNext()) {
967 NamedDecl *del = filter.next()->getUnderlyingDecl();
969 // C++0x [basic.stc.dynamic.deallocation]p2:
970 // A template instance is never a usual deallocation function,
971 // regardless of its signature.
972 if (isa<FunctionTemplateDecl>(del)) {
977 // C++0x [basic.stc.dynamic.deallocation]p2:
978 // If class T does not declare [an operator delete[] with one
979 // parameter] but does declare a member deallocation function
980 // named operator delete[] with exactly two parameters, the
981 // second of which has type std::size_t, then this function
982 // is a usual deallocation function.
983 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
990 if (!ops.isSingleResult()) return false;
992 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
993 return (del->getNumParams() == 2);
996 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
999 /// @code new (memory) int[size][4] @endcode
1001 /// @code ::new Foo(23, "hello") @endcode
1003 /// \param StartLoc The first location of the expression.
1004 /// \param UseGlobal True if 'new' was prefixed with '::'.
1005 /// \param PlacementLParen Opening paren of the placement arguments.
1006 /// \param PlacementArgs Placement new arguments.
1007 /// \param PlacementRParen Closing paren of the placement arguments.
1008 /// \param TypeIdParens If the type is in parens, the source range.
1009 /// \param D The type to be allocated, as well as array dimensions.
1010 /// \param Initializer The initializing expression or initializer-list, or null
1011 /// if there is none.
1013 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1014 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1015 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1016 Declarator &D, Expr *Initializer) {
1017 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1019 Expr *ArraySize = 0;
1020 // If the specified type is an array, unwrap it and save the expression.
1021 if (D.getNumTypeObjects() > 0 &&
1022 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1023 DeclaratorChunk &Chunk = D.getTypeObject(0);
1024 if (TypeContainsAuto)
1025 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1026 << D.getSourceRange());
1027 if (Chunk.Arr.hasStatic)
1028 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1029 << D.getSourceRange());
1030 if (!Chunk.Arr.NumElts)
1031 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1032 << D.getSourceRange());
1034 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1035 D.DropFirstTypeObject();
1038 // Every dimension shall be of constant size.
1040 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1041 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1044 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1045 if (Expr *NumElts = (Expr *)Array.NumElts) {
1046 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1047 if (getLangOpts().CPlusPlus1y) {
1048 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1049 // shall be a converted constant expression (5.19) of type std::size_t
1050 // and shall evaluate to a strictly positive value.
1051 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1052 assert(IntWidth && "Builtin type of size 0?");
1053 llvm::APSInt Value(IntWidth);
1055 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1060 = VerifyIntegerConstantExpression(NumElts, 0,
1061 diag::err_new_array_nonconst)
1071 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
1072 QualType AllocType = TInfo->getType();
1073 if (D.isInvalidType())
1076 SourceRange DirectInitRange;
1077 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1078 DirectInitRange = List->getSourceRange();
1080 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1093 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1097 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1098 return PLE->getNumExprs() == 0;
1099 if (isa<ImplicitValueInitExpr>(Init))
1101 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1102 return !CCE->isListInitialization() &&
1103 CCE->getConstructor()->isDefaultConstructor();
1104 else if (Style == CXXNewExpr::ListInit) {
1105 assert(isa<InitListExpr>(Init) &&
1106 "Shouldn't create list CXXConstructExprs for arrays.");
1113 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1114 SourceLocation PlacementLParen,
1115 MultiExprArg PlacementArgs,
1116 SourceLocation PlacementRParen,
1117 SourceRange TypeIdParens,
1119 TypeSourceInfo *AllocTypeInfo,
1121 SourceRange DirectInitRange,
1123 bool TypeMayContainAuto) {
1124 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1125 SourceLocation StartLoc = Range.getBegin();
1127 CXXNewExpr::InitializationStyle initStyle;
1128 if (DirectInitRange.isValid()) {
1129 assert(Initializer && "Have parens but no initializer.");
1130 initStyle = CXXNewExpr::CallInit;
1131 } else if (Initializer && isa<InitListExpr>(Initializer))
1132 initStyle = CXXNewExpr::ListInit;
1134 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1135 isa<CXXConstructExpr>(Initializer)) &&
1136 "Initializer expression that cannot have been implicitly created.");
1137 initStyle = CXXNewExpr::NoInit;
1140 Expr **Inits = &Initializer;
1141 unsigned NumInits = Initializer ? 1 : 0;
1142 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1143 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1144 Inits = List->getExprs();
1145 NumInits = List->getNumExprs();
1148 // Determine whether we've already built the initializer.
1149 bool HaveCompleteInit = false;
1150 if (Initializer && isa<CXXConstructExpr>(Initializer) &&
1151 !isa<CXXTemporaryObjectExpr>(Initializer))
1152 HaveCompleteInit = true;
1153 else if (Initializer && isa<ImplicitValueInitExpr>(Initializer))
1154 HaveCompleteInit = true;
1156 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1157 if (TypeMayContainAuto && AllocType->isUndeducedType()) {
1158 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1159 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1160 << AllocType << TypeRange);
1161 if (initStyle == CXXNewExpr::ListInit)
1162 return ExprError(Diag(Inits[0]->getLocStart(),
1163 diag::err_auto_new_requires_parens)
1164 << AllocType << TypeRange);
1166 Expr *FirstBad = Inits[1];
1167 return ExprError(Diag(FirstBad->getLocStart(),
1168 diag::err_auto_new_ctor_multiple_expressions)
1169 << AllocType << TypeRange);
1171 Expr *Deduce = Inits[0];
1172 QualType DeducedType;
1173 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1174 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1175 << AllocType << Deduce->getType()
1176 << TypeRange << Deduce->getSourceRange());
1177 if (DeducedType.isNull())
1179 AllocType = DeducedType;
1182 // Per C++0x [expr.new]p5, the type being constructed may be a
1183 // typedef of an array type.
1185 if (const ConstantArrayType *Array
1186 = Context.getAsConstantArrayType(AllocType)) {
1187 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1188 Context.getSizeType(),
1189 TypeRange.getEnd());
1190 AllocType = Array->getElementType();
1194 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1197 if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
1198 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1199 diag::warn_dangling_std_initializer_list)
1200 << /*at end of FE*/0 << Inits[0]->getSourceRange();
1203 // In ARC, infer 'retaining' for the allocated
1204 if (getLangOpts().ObjCAutoRefCount &&
1205 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1206 AllocType->isObjCLifetimeType()) {
1207 AllocType = Context.getLifetimeQualifiedType(AllocType,
1208 AllocType->getObjCARCImplicitLifetime());
1211 QualType ResultType = Context.getPointerType(AllocType);
1213 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1214 ExprResult result = CheckPlaceholderExpr(ArraySize);
1215 if (result.isInvalid()) return ExprError();
1216 ArraySize = result.take();
1218 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1219 // integral or enumeration type with a non-negative value."
1220 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1221 // enumeration type, or a class type for which a single non-explicit
1222 // conversion function to integral or unscoped enumeration type exists.
1223 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1225 if (ArraySize && !ArraySize->isTypeDependent()) {
1226 ExprResult ConvertedSize;
1227 if (getLangOpts().CPlusPlus1y) {
1228 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1229 assert(IntWidth && "Builtin type of size 0?");
1230 llvm::APSInt Value(IntWidth);
1231 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1234 if (!ConvertedSize.isInvalid() &&
1235 ArraySize->getType()->getAs<RecordType>())
1236 // Diagnose the compatibility of this conversion.
1237 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1238 << ArraySize->getType() << 0 << "'size_t'";
1240 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1245 SizeConvertDiagnoser(Expr *ArraySize)
1246 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1247 ArraySize(ArraySize) {}
1249 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1251 return S.Diag(Loc, diag::err_array_size_not_integral)
1252 << S.getLangOpts().CPlusPlus11 << T;
1255 virtual SemaDiagnosticBuilder diagnoseIncomplete(
1256 Sema &S, SourceLocation Loc, QualType T) {
1257 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1258 << T << ArraySize->getSourceRange();
1261 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
1262 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
1263 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1266 virtual SemaDiagnosticBuilder noteExplicitConv(
1267 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
1268 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1269 << ConvTy->isEnumeralType() << ConvTy;
1272 virtual SemaDiagnosticBuilder diagnoseAmbiguous(
1273 Sema &S, SourceLocation Loc, QualType T) {
1274 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1277 virtual SemaDiagnosticBuilder noteAmbiguous(
1278 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
1279 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1280 << ConvTy->isEnumeralType() << ConvTy;
1283 virtual SemaDiagnosticBuilder diagnoseConversion(
1284 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
1286 S.getLangOpts().CPlusPlus11
1287 ? diag::warn_cxx98_compat_array_size_conversion
1288 : diag::ext_array_size_conversion)
1289 << T << ConvTy->isEnumeralType() << ConvTy;
1291 } SizeDiagnoser(ArraySize);
1293 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1296 if (ConvertedSize.isInvalid())
1299 ArraySize = ConvertedSize.take();
1300 QualType SizeType = ArraySize->getType();
1302 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1305 // C++98 [expr.new]p7:
1306 // The expression in a direct-new-declarator shall have integral type
1307 // with a non-negative value.
1309 // Let's see if this is a constant < 0. If so, we reject it out of
1310 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1313 // Note: such a construct has well-defined semantics in C++11: it throws
1314 // std::bad_array_new_length.
1315 if (!ArraySize->isValueDependent()) {
1317 // We've already performed any required implicit conversion to integer or
1318 // unscoped enumeration type.
1319 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1320 if (Value < llvm::APSInt(
1321 llvm::APInt::getNullValue(Value.getBitWidth()),
1322 Value.isUnsigned())) {
1323 if (getLangOpts().CPlusPlus11)
1324 Diag(ArraySize->getLocStart(),
1325 diag::warn_typecheck_negative_array_new_size)
1326 << ArraySize->getSourceRange();
1328 return ExprError(Diag(ArraySize->getLocStart(),
1329 diag::err_typecheck_negative_array_size)
1330 << ArraySize->getSourceRange());
1331 } else if (!AllocType->isDependentType()) {
1332 unsigned ActiveSizeBits =
1333 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1334 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1335 if (getLangOpts().CPlusPlus11)
1336 Diag(ArraySize->getLocStart(),
1337 diag::warn_array_new_too_large)
1338 << Value.toString(10)
1339 << ArraySize->getSourceRange();
1341 return ExprError(Diag(ArraySize->getLocStart(),
1342 diag::err_array_too_large)
1343 << Value.toString(10)
1344 << ArraySize->getSourceRange());
1347 } else if (TypeIdParens.isValid()) {
1348 // Can't have dynamic array size when the type-id is in parentheses.
1349 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1350 << ArraySize->getSourceRange()
1351 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1352 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1354 TypeIdParens = SourceRange();
1358 // Note that we do *not* convert the argument in any way. It can
1359 // be signed, larger than size_t, whatever.
1362 FunctionDecl *OperatorNew = 0;
1363 FunctionDecl *OperatorDelete = 0;
1365 if (!AllocType->isDependentType() &&
1366 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1367 FindAllocationFunctions(StartLoc,
1368 SourceRange(PlacementLParen, PlacementRParen),
1369 UseGlobal, AllocType, ArraySize, PlacementArgs,
1370 OperatorNew, OperatorDelete))
1373 // If this is an array allocation, compute whether the usual array
1374 // deallocation function for the type has a size_t parameter.
1375 bool UsualArrayDeleteWantsSize = false;
1376 if (ArraySize && !AllocType->isDependentType())
1377 UsualArrayDeleteWantsSize
1378 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1380 SmallVector<Expr *, 8> AllPlaceArgs;
1382 // Add default arguments, if any.
1383 const FunctionProtoType *Proto =
1384 OperatorNew->getType()->getAs<FunctionProtoType>();
1385 VariadicCallType CallType =
1386 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
1388 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
1389 PlacementArgs, AllPlaceArgs, CallType))
1392 if (!AllPlaceArgs.empty())
1393 PlacementArgs = AllPlaceArgs;
1395 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
1397 // FIXME: Missing call to CheckFunctionCall or equivalent
1400 // Warn if the type is over-aligned and is being allocated by global operator
1402 if (PlacementArgs.empty() && OperatorNew &&
1403 (OperatorNew->isImplicit() ||
1404 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1405 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1406 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1407 if (Align > SuitableAlign)
1408 Diag(StartLoc, diag::warn_overaligned_type)
1410 << unsigned(Align / Context.getCharWidth())
1411 << unsigned(SuitableAlign / Context.getCharWidth());
1415 QualType InitType = AllocType;
1416 // Array 'new' can't have any initializers except empty parentheses.
1417 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1418 // dialect distinction.
1419 if (ResultType->isArrayType() || ArraySize) {
1420 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1421 SourceRange InitRange(Inits[0]->getLocStart(),
1422 Inits[NumInits - 1]->getLocEnd());
1423 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1426 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1427 // We do the initialization typechecking against the array type
1428 // corresponding to the number of initializers + 1 (to also check
1429 // default-initialization).
1430 unsigned NumElements = ILE->getNumInits() + 1;
1431 InitType = Context.getConstantArrayType(AllocType,
1432 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1433 ArrayType::Normal, 0);
1437 // If we can perform the initialization, and we've not already done so,
1439 if (!AllocType->isDependentType() &&
1440 !Expr::hasAnyTypeDependentArguments(
1441 llvm::makeArrayRef(Inits, NumInits)) &&
1442 !HaveCompleteInit) {
1443 // C++11 [expr.new]p15:
1444 // A new-expression that creates an object of type T initializes that
1445 // object as follows:
1446 InitializationKind Kind
1447 // - If the new-initializer is omitted, the object is default-
1448 // initialized (8.5); if no initialization is performed,
1449 // the object has indeterminate value
1450 = initStyle == CXXNewExpr::NoInit
1451 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1452 // - Otherwise, the new-initializer is interpreted according to the
1453 // initialization rules of 8.5 for direct-initialization.
1454 : initStyle == CXXNewExpr::ListInit
1455 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1456 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1457 DirectInitRange.getBegin(),
1458 DirectInitRange.getEnd());
1460 InitializedEntity Entity
1461 = InitializedEntity::InitializeNew(StartLoc, InitType);
1462 InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1463 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1464 MultiExprArg(Inits, NumInits));
1465 if (FullInit.isInvalid())
1468 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1469 // we don't want the initialized object to be destructed.
1470 if (CXXBindTemporaryExpr *Binder =
1471 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1472 FullInit = Owned(Binder->getSubExpr());
1474 Initializer = FullInit.take();
1477 // Mark the new and delete operators as referenced.
1479 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1481 MarkFunctionReferenced(StartLoc, OperatorNew);
1483 if (OperatorDelete) {
1484 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1486 MarkFunctionReferenced(StartLoc, OperatorDelete);
1489 // C++0x [expr.new]p17:
1490 // If the new expression creates an array of objects of class type,
1491 // access and ambiguity control are done for the destructor.
1492 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1493 if (ArraySize && !BaseAllocType->isDependentType()) {
1494 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1495 if (CXXDestructorDecl *dtor = LookupDestructor(
1496 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1497 MarkFunctionReferenced(StartLoc, dtor);
1498 CheckDestructorAccess(StartLoc, dtor,
1499 PDiag(diag::err_access_dtor)
1501 if (DiagnoseUseOfDecl(dtor, StartLoc))
1507 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1509 UsualArrayDeleteWantsSize,
1510 PlacementArgs, TypeIdParens,
1511 ArraySize, initStyle, Initializer,
1512 ResultType, AllocTypeInfo,
1513 Range, DirectInitRange));
1516 /// \brief Checks that a type is suitable as the allocated type
1517 /// in a new-expression.
1518 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1520 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1521 // abstract class type or array thereof.
1522 if (AllocType->isFunctionType())
1523 return Diag(Loc, diag::err_bad_new_type)
1524 << AllocType << 0 << R;
1525 else if (AllocType->isReferenceType())
1526 return Diag(Loc, diag::err_bad_new_type)
1527 << AllocType << 1 << R;
1528 else if (!AllocType->isDependentType() &&
1529 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
1531 else if (RequireNonAbstractType(Loc, AllocType,
1532 diag::err_allocation_of_abstract_type))
1534 else if (AllocType->isVariablyModifiedType())
1535 return Diag(Loc, diag::err_variably_modified_new_type)
1537 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1538 return Diag(Loc, diag::err_address_space_qualified_new)
1539 << AllocType.getUnqualifiedType() << AddressSpace;
1540 else if (getLangOpts().ObjCAutoRefCount) {
1541 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1542 QualType BaseAllocType = Context.getBaseElementType(AT);
1543 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1544 BaseAllocType->isObjCLifetimeType())
1545 return Diag(Loc, diag::err_arc_new_array_without_ownership)
1553 /// \brief Determine whether the given function is a non-placement
1554 /// deallocation function.
1555 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1556 if (FD->isInvalidDecl())
1559 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1560 return Method->isUsualDeallocationFunction();
1562 if (FD->getOverloadedOperator() != OO_Delete &&
1563 FD->getOverloadedOperator() != OO_Array_Delete)
1566 if (FD->getNumParams() == 1)
1569 return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
1570 S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
1571 S.Context.getSizeType());
1574 /// FindAllocationFunctions - Finds the overloads of operator new and delete
1575 /// that are appropriate for the allocation.
1576 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1577 bool UseGlobal, QualType AllocType,
1578 bool IsArray, MultiExprArg PlaceArgs,
1579 FunctionDecl *&OperatorNew,
1580 FunctionDecl *&OperatorDelete) {
1581 // --- Choosing an allocation function ---
1582 // C++ 5.3.4p8 - 14 & 18
1583 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1584 // in the scope of the allocated class.
1585 // 2) If an array size is given, look for operator new[], else look for
1587 // 3) The first argument is always size_t. Append the arguments from the
1590 SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
1591 // We don't care about the actual value of this argument.
1592 // FIXME: Should the Sema create the expression and embed it in the syntax
1593 // tree? Or should the consumer just recalculate the value?
1594 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1595 Context.getTargetInfo().getPointerWidth(0)),
1596 Context.getSizeType(),
1598 AllocArgs[0] = &Size;
1599 std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
1601 // C++ [expr.new]p8:
1602 // If the allocated type is a non-array type, the allocation
1603 // function's name is operator new and the deallocation function's
1604 // name is operator delete. If the allocated type is an array
1605 // type, the allocation function's name is operator new[] and the
1606 // deallocation function's name is operator delete[].
1607 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1608 IsArray ? OO_Array_New : OO_New);
1609 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1610 IsArray ? OO_Array_Delete : OO_Delete);
1612 QualType AllocElemType = Context.getBaseElementType(AllocType);
1614 if (AllocElemType->isRecordType() && !UseGlobal) {
1615 CXXRecordDecl *Record
1616 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1617 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
1618 /*AllowMissing=*/true, OperatorNew))
1623 // Didn't find a member overload. Look for a global one.
1624 DeclareGlobalNewDelete();
1625 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1626 bool FallbackEnabled = IsArray && Context.getLangOpts().MicrosoftMode;
1627 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
1628 /*AllowMissing=*/FallbackEnabled, OperatorNew,
1629 /*Diagnose=*/!FallbackEnabled)) {
1630 if (!FallbackEnabled)
1633 // MSVC will fall back on trying to find a matching global operator new
1634 // if operator new[] cannot be found. Also, MSVC will leak by not
1635 // generating a call to operator delete or operator delete[], but we
1636 // will not replicate that bug.
1637 NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
1638 DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1639 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
1640 /*AllowMissing=*/false, OperatorNew))
1645 // We don't need an operator delete if we're running under
1647 if (!getLangOpts().Exceptions) {
1652 // FindAllocationOverload can change the passed in arguments, so we need to
1654 if (!PlaceArgs.empty())
1655 std::copy(AllocArgs.begin() + 1, AllocArgs.end(), PlaceArgs.data());
1657 // C++ [expr.new]p19:
1659 // If the new-expression begins with a unary :: operator, the
1660 // deallocation function's name is looked up in the global
1661 // scope. Otherwise, if the allocated type is a class type T or an
1662 // array thereof, the deallocation function's name is looked up in
1663 // the scope of T. If this lookup fails to find the name, or if
1664 // the allocated type is not a class type or array thereof, the
1665 // deallocation function's name is looked up in the global scope.
1666 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1667 if (AllocElemType->isRecordType() && !UseGlobal) {
1669 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1670 LookupQualifiedName(FoundDelete, RD);
1672 if (FoundDelete.isAmbiguous())
1673 return true; // FIXME: clean up expressions?
1675 if (FoundDelete.empty()) {
1676 DeclareGlobalNewDelete();
1677 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1680 FoundDelete.suppressDiagnostics();
1682 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1684 // Whether we're looking for a placement operator delete is dictated
1685 // by whether we selected a placement operator new, not by whether
1686 // we had explicit placement arguments. This matters for things like
1687 // struct A { void *operator new(size_t, int = 0); ... };
1689 bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
1691 if (isPlacementNew) {
1692 // C++ [expr.new]p20:
1693 // A declaration of a placement deallocation function matches the
1694 // declaration of a placement allocation function if it has the
1695 // same number of parameters and, after parameter transformations
1696 // (8.3.5), all parameter types except the first are
1699 // To perform this comparison, we compute the function type that
1700 // the deallocation function should have, and use that type both
1701 // for template argument deduction and for comparison purposes.
1703 // FIXME: this comparison should ignore CC and the like.
1704 QualType ExpectedFunctionType;
1706 const FunctionProtoType *Proto
1707 = OperatorNew->getType()->getAs<FunctionProtoType>();
1709 SmallVector<QualType, 4> ArgTypes;
1710 ArgTypes.push_back(Context.VoidPtrTy);
1711 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1712 ArgTypes.push_back(Proto->getArgType(I));
1714 FunctionProtoType::ExtProtoInfo EPI;
1715 EPI.Variadic = Proto->isVariadic();
1717 ExpectedFunctionType
1718 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
1721 for (LookupResult::iterator D = FoundDelete.begin(),
1722 DEnd = FoundDelete.end();
1724 FunctionDecl *Fn = 0;
1725 if (FunctionTemplateDecl *FnTmpl
1726 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1727 // Perform template argument deduction to try to match the
1728 // expected function type.
1729 TemplateDeductionInfo Info(StartLoc);
1730 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1733 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1735 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1736 Matches.push_back(std::make_pair(D.getPair(), Fn));
1739 // C++ [expr.new]p20:
1740 // [...] Any non-placement deallocation function matches a
1741 // non-placement allocation function. [...]
1742 for (LookupResult::iterator D = FoundDelete.begin(),
1743 DEnd = FoundDelete.end();
1745 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1746 if (isNonPlacementDeallocationFunction(*this, Fn))
1747 Matches.push_back(std::make_pair(D.getPair(), Fn));
1750 // C++1y [expr.new]p22:
1751 // For a non-placement allocation function, the normal deallocation
1752 // function lookup is used
1753 // C++1y [expr.delete]p?:
1754 // If [...] deallocation function lookup finds both a usual deallocation
1755 // function with only a pointer parameter and a usual deallocation
1756 // function with both a pointer parameter and a size parameter, then the
1757 // selected deallocation function shall be the one with two parameters.
1758 // Otherwise, the selected deallocation function shall be the function
1759 // with one parameter.
1760 if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
1761 if (Matches[0].second->getNumParams() == 1)
1762 Matches.erase(Matches.begin());
1764 Matches.erase(Matches.begin() + 1);
1765 assert(Matches[0].second->getNumParams() == 2 &&
1766 "found an unexpected uusal deallocation function");
1770 // C++ [expr.new]p20:
1771 // [...] If the lookup finds a single matching deallocation
1772 // function, that function will be called; otherwise, no
1773 // deallocation function will be called.
1774 if (Matches.size() == 1) {
1775 OperatorDelete = Matches[0].second;
1777 // C++0x [expr.new]p20:
1778 // If the lookup finds the two-parameter form of a usual
1779 // deallocation function (3.7.4.2) and that function, considered
1780 // as a placement deallocation function, would have been
1781 // selected as a match for the allocation function, the program
1783 if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
1784 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
1785 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1786 << SourceRange(PlaceArgs.front()->getLocStart(),
1787 PlaceArgs.back()->getLocEnd());
1788 if (!OperatorDelete->isImplicit())
1789 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1792 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1800 /// FindAllocationOverload - Find an fitting overload for the allocation
1801 /// function in the specified scope.
1802 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1803 DeclarationName Name, MultiExprArg Args,
1805 bool AllowMissing, FunctionDecl *&Operator,
1807 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1808 LookupQualifiedName(R, Ctx);
1810 if (AllowMissing || !Diagnose)
1812 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1816 if (R.isAmbiguous())
1819 R.suppressDiagnostics();
1821 OverloadCandidateSet Candidates(StartLoc);
1822 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1823 Alloc != AllocEnd; ++Alloc) {
1824 // Even member operator new/delete are implicitly treated as
1825 // static, so don't use AddMemberCandidate.
1826 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1828 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1829 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1830 /*ExplicitTemplateArgs=*/0,
1832 /*SuppressUserConversions=*/false);
1836 FunctionDecl *Fn = cast<FunctionDecl>(D);
1837 AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
1838 /*SuppressUserConversions=*/false);
1841 // Do the resolution.
1842 OverloadCandidateSet::iterator Best;
1843 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1846 FunctionDecl *FnDecl = Best->Function;
1847 MarkFunctionReferenced(StartLoc, FnDecl);
1848 // The first argument is size_t, and the first parameter must be size_t,
1849 // too. This is checked on declaration and can be assumed. (It can't be
1850 // asserted on, though, since invalid decls are left in there.)
1851 // Watch out for variadic allocator function.
1852 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1853 for (unsigned i = 0; (i < Args.size() && i < NumArgsInFnDecl); ++i) {
1854 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1855 FnDecl->getParamDecl(i));
1857 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1861 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
1862 if (Result.isInvalid())
1865 Args[i] = Result.takeAs<Expr>();
1870 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1871 Best->FoundDecl, Diagnose) == AR_inaccessible)
1877 case OR_No_Viable_Function:
1879 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1881 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
1887 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1889 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
1895 Diag(StartLoc, diag::err_ovl_deleted_call)
1896 << Best->Function->isDeleted()
1898 << getDeletedOrUnavailableSuffix(Best->Function)
1900 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
1905 llvm_unreachable("Unreachable, bad result from BestViableFunction");
1909 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
1910 /// delete. These are:
1913 /// void* operator new(std::size_t) throw(std::bad_alloc);
1914 /// void* operator new[](std::size_t) throw(std::bad_alloc);
1915 /// void operator delete(void *) throw();
1916 /// void operator delete[](void *) throw();
1918 /// void* operator new(std::size_t);
1919 /// void* operator new[](std::size_t);
1920 /// void operator delete(void *) noexcept;
1921 /// void operator delete[](void *) noexcept;
1923 /// void* operator new(std::size_t);
1924 /// void* operator new[](std::size_t);
1925 /// void operator delete(void *) noexcept;
1926 /// void operator delete[](void *) noexcept;
1927 /// void operator delete(void *, std::size_t) noexcept;
1928 /// void operator delete[](void *, std::size_t) noexcept;
1930 /// Note that the placement and nothrow forms of new are *not* implicitly
1931 /// declared. Their use requires including \<new\>.
1932 void Sema::DeclareGlobalNewDelete() {
1933 if (GlobalNewDeleteDeclared)
1936 // C++ [basic.std.dynamic]p2:
1937 // [...] The following allocation and deallocation functions (18.4) are
1938 // implicitly declared in global scope in each translation unit of a
1942 // void* operator new(std::size_t) throw(std::bad_alloc);
1943 // void* operator new[](std::size_t) throw(std::bad_alloc);
1944 // void operator delete(void*) throw();
1945 // void operator delete[](void*) throw();
1947 // void* operator new(std::size_t);
1948 // void* operator new[](std::size_t);
1949 // void operator delete(void*) noexcept;
1950 // void operator delete[](void*) noexcept;
1952 // void* operator new(std::size_t);
1953 // void* operator new[](std::size_t);
1954 // void operator delete(void*) noexcept;
1955 // void operator delete[](void*) noexcept;
1956 // void operator delete(void*, std::size_t) noexcept;
1957 // void operator delete[](void*, std::size_t) noexcept;
1959 // These implicit declarations introduce only the function names operator
1960 // new, operator new[], operator delete, operator delete[].
1962 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1963 // "std" or "bad_alloc" as necessary to form the exception specification.
1964 // However, we do not make these implicit declarations visible to name
1966 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
1967 // The "std::bad_alloc" class has not yet been declared, so build it
1969 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1970 getOrCreateStdNamespace(),
1971 SourceLocation(), SourceLocation(),
1972 &PP.getIdentifierTable().get("bad_alloc"),
1974 getStdBadAlloc()->setImplicit(true);
1977 GlobalNewDeleteDeclared = true;
1979 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1980 QualType SizeT = Context.getSizeType();
1981 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
1983 DeclareGlobalAllocationFunction(
1984 Context.DeclarationNames.getCXXOperatorName(OO_New),
1985 VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
1986 DeclareGlobalAllocationFunction(
1987 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1988 VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
1989 DeclareGlobalAllocationFunction(
1990 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1991 Context.VoidTy, VoidPtr);
1992 DeclareGlobalAllocationFunction(
1993 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1994 Context.VoidTy, VoidPtr);
1995 if (getLangOpts().SizedDeallocation) {
1996 DeclareGlobalAllocationFunction(
1997 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1998 Context.VoidTy, VoidPtr, Context.getSizeType());
1999 DeclareGlobalAllocationFunction(
2000 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2001 Context.VoidTy, VoidPtr, Context.getSizeType());
2005 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2006 /// allocation function if it doesn't already exist.
2007 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2009 QualType Param1, QualType Param2,
2010 bool AddMallocAttr) {
2011 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2012 unsigned NumParams = Param2.isNull() ? 1 : 2;
2014 // Check if this function is already declared.
2015 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2016 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2017 Alloc != AllocEnd; ++Alloc) {
2018 // Only look at non-template functions, as it is the predefined,
2019 // non-templated allocation function we are trying to declare here.
2020 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2021 if (Func->getNumParams() == NumParams) {
2022 QualType InitialParam1Type =
2023 Context.getCanonicalType(Func->getParamDecl(0)
2024 ->getType().getUnqualifiedType());
2025 QualType InitialParam2Type =
2027 ? Context.getCanonicalType(Func->getParamDecl(1)
2028 ->getType().getUnqualifiedType())
2030 // FIXME: Do we need to check for default arguments here?
2031 if (InitialParam1Type == Param1 &&
2032 (NumParams == 1 || InitialParam2Type == Param2)) {
2033 if (AddMallocAttr && !Func->hasAttr<MallocAttr>())
2034 Func->addAttr(::new (Context) MallocAttr(SourceLocation(),
2036 // Make the function visible to name lookup, even if we found it in
2037 // an unimported module. It either is an implicitly-declared global
2038 // allocation function, or is suppressing that function.
2039 Func->setHidden(false);
2046 QualType BadAllocType;
2047 bool HasBadAllocExceptionSpec
2048 = (Name.getCXXOverloadedOperator() == OO_New ||
2049 Name.getCXXOverloadedOperator() == OO_Array_New);
2050 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus11) {
2051 assert(StdBadAlloc && "Must have std::bad_alloc declared");
2052 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2055 FunctionProtoType::ExtProtoInfo EPI;
2056 if (HasBadAllocExceptionSpec) {
2057 if (!getLangOpts().CPlusPlus11) {
2058 EPI.ExceptionSpecType = EST_Dynamic;
2059 EPI.NumExceptions = 1;
2060 EPI.Exceptions = &BadAllocType;
2063 EPI.ExceptionSpecType = getLangOpts().CPlusPlus11 ?
2064 EST_BasicNoexcept : EST_DynamicNone;
2067 QualType Params[] = { Param1, Param2 };
2069 QualType FnType = Context.getFunctionType(
2070 Return, ArrayRef<QualType>(Params, NumParams), EPI);
2071 FunctionDecl *Alloc =
2072 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2073 SourceLocation(), Name,
2074 FnType, /*TInfo=*/0, SC_None, false, true);
2075 Alloc->setImplicit();
2078 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
2080 ParmVarDecl *ParamDecls[2];
2081 for (unsigned I = 0; I != NumParams; ++I)
2082 ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
2083 SourceLocation(), 0,
2084 Params[I], /*TInfo=*/0,
2086 Alloc->setParams(ArrayRef<ParmVarDecl*>(ParamDecls, NumParams));
2088 // FIXME: Also add this declaration to the IdentifierResolver, but
2089 // make sure it is at the end of the chain to coincide with the
2091 Context.getTranslationUnitDecl()->addDecl(Alloc);
2094 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2095 bool CanProvideSize,
2096 DeclarationName Name) {
2097 DeclareGlobalNewDelete();
2099 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2100 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2102 // C++ [expr.new]p20:
2103 // [...] Any non-placement deallocation function matches a
2104 // non-placement allocation function. [...]
2105 llvm::SmallVector<FunctionDecl*, 2> Matches;
2106 for (LookupResult::iterator D = FoundDelete.begin(),
2107 DEnd = FoundDelete.end();
2109 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
2110 if (isNonPlacementDeallocationFunction(*this, Fn))
2111 Matches.push_back(Fn);
2114 // C++1y [expr.delete]p?:
2115 // If the type is complete and deallocation function lookup finds both a
2116 // usual deallocation function with only a pointer parameter and a usual
2117 // deallocation function with both a pointer parameter and a size
2118 // parameter, then the selected deallocation function shall be the one
2119 // with two parameters. Otherwise, the selected deallocation function
2120 // shall be the function with one parameter.
2121 if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
2122 unsigned NumArgs = CanProvideSize ? 2 : 1;
2123 if (Matches[0]->getNumParams() != NumArgs)
2124 Matches.erase(Matches.begin());
2126 Matches.erase(Matches.begin() + 1);
2127 assert(Matches[0]->getNumParams() == NumArgs &&
2128 "found an unexpected uusal deallocation function");
2131 assert(Matches.size() == 1 &&
2132 "unexpectedly have multiple usual deallocation functions");
2133 return Matches.front();
2136 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2137 DeclarationName Name,
2138 FunctionDecl* &Operator, bool Diagnose) {
2139 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2140 // Try to find operator delete/operator delete[] in class scope.
2141 LookupQualifiedName(Found, RD);
2143 if (Found.isAmbiguous())
2146 Found.suppressDiagnostics();
2148 SmallVector<DeclAccessPair,4> Matches;
2149 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2151 NamedDecl *ND = (*F)->getUnderlyingDecl();
2153 // Ignore template operator delete members from the check for a usual
2154 // deallocation function.
2155 if (isa<FunctionTemplateDecl>(ND))
2158 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
2159 Matches.push_back(F.getPair());
2162 // There's exactly one suitable operator; pick it.
2163 if (Matches.size() == 1) {
2164 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
2166 if (Operator->isDeleted()) {
2168 Diag(StartLoc, diag::err_deleted_function_use);
2169 NoteDeletedFunction(Operator);
2174 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2175 Matches[0], Diagnose) == AR_inaccessible)
2180 // We found multiple suitable operators; complain about the ambiguity.
2181 } else if (!Matches.empty()) {
2183 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2186 for (SmallVectorImpl<DeclAccessPair>::iterator
2187 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2188 Diag((*F)->getUnderlyingDecl()->getLocation(),
2189 diag::note_member_declared_here) << Name;
2194 // We did find operator delete/operator delete[] declarations, but
2195 // none of them were suitable.
2196 if (!Found.empty()) {
2198 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2201 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2203 Diag((*F)->getUnderlyingDecl()->getLocation(),
2204 diag::note_member_declared_here) << Name;
2213 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2214 /// @code ::delete ptr; @endcode
2216 /// @code delete [] ptr; @endcode
2218 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
2219 bool ArrayForm, Expr *ExE) {
2220 // C++ [expr.delete]p1:
2221 // The operand shall have a pointer type, or a class type having a single
2222 // non-explicit conversion function to a pointer type. The result has type
2225 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2227 ExprResult Ex = Owned(ExE);
2228 FunctionDecl *OperatorDelete = 0;
2229 bool ArrayFormAsWritten = ArrayForm;
2230 bool UsualArrayDeleteWantsSize = false;
2232 if (!Ex.get()->isTypeDependent()) {
2233 // Perform lvalue-to-rvalue cast, if needed.
2234 Ex = DefaultLvalueConversion(Ex.take());
2238 QualType Type = Ex.get()->getType();
2240 class DeleteConverter : public ContextualImplicitConverter {
2242 DeleteConverter() : ContextualImplicitConverter(false, true) {}
2244 bool match(QualType ConvType) {
2245 // FIXME: If we have an operator T* and an operator void*, we must pick
2247 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
2248 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
2253 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2255 return S.Diag(Loc, diag::err_delete_operand) << T;
2258 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2260 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
2263 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2264 QualType T, QualType ConvTy) {
2265 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
2268 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2270 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2274 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2276 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
2279 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2281 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2285 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2286 QualType T, QualType ConvTy) {
2287 llvm_unreachable("conversion functions are permitted");
2291 Ex = PerformContextualImplicitConversion(StartLoc, Ex.take(), Converter);
2294 Type = Ex.get()->getType();
2295 if (!Converter.match(Type))
2296 // FIXME: PerformContextualImplicitConversion should return ExprError
2297 // itself in this case.
2300 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
2301 QualType PointeeElem = Context.getBaseElementType(Pointee);
2303 if (unsigned AddressSpace = Pointee.getAddressSpace())
2304 return Diag(Ex.get()->getLocStart(),
2305 diag::err_address_space_qualified_delete)
2306 << Pointee.getUnqualifiedType() << AddressSpace;
2308 CXXRecordDecl *PointeeRD = 0;
2309 if (Pointee->isVoidType() && !isSFINAEContext()) {
2310 // The C++ standard bans deleting a pointer to a non-object type, which
2311 // effectively bans deletion of "void*". However, most compilers support
2312 // this, so we treat it as a warning unless we're in a SFINAE context.
2313 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
2314 << Type << Ex.get()->getSourceRange();
2315 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
2316 return ExprError(Diag(StartLoc, diag::err_delete_operand)
2317 << Type << Ex.get()->getSourceRange());
2318 } else if (!Pointee->isDependentType()) {
2319 if (!RequireCompleteType(StartLoc, Pointee,
2320 diag::warn_delete_incomplete, Ex.get())) {
2321 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2322 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2326 // C++ [expr.delete]p2:
2327 // [Note: a pointer to a const type can be the operand of a
2328 // delete-expression; it is not necessary to cast away the constness
2329 // (5.2.11) of the pointer expression before it is used as the operand
2330 // of the delete-expression. ]
2332 if (Pointee->isArrayType() && !ArrayForm) {
2333 Diag(StartLoc, diag::warn_delete_array_type)
2334 << Type << Ex.get()->getSourceRange()
2335 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2339 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2340 ArrayForm ? OO_Array_Delete : OO_Delete);
2344 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2348 // If we're allocating an array of records, check whether the
2349 // usual operator delete[] has a size_t parameter.
2351 // If the user specifically asked to use the global allocator,
2352 // we'll need to do the lookup into the class.
2354 UsualArrayDeleteWantsSize =
2355 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2357 // Otherwise, the usual operator delete[] should be the
2358 // function we just found.
2359 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
2360 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2363 if (!PointeeRD->hasIrrelevantDestructor())
2364 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2365 MarkFunctionReferenced(StartLoc,
2366 const_cast<CXXDestructorDecl*>(Dtor));
2367 if (DiagnoseUseOfDecl(Dtor, StartLoc))
2371 // C++ [expr.delete]p3:
2372 // In the first alternative (delete object), if the static type of the
2373 // object to be deleted is different from its dynamic type, the static
2374 // type shall be a base class of the dynamic type of the object to be
2375 // deleted and the static type shall have a virtual destructor or the
2376 // behavior is undefined.
2378 // Note: a final class cannot be derived from, no issue there
2379 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
2380 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
2381 if (dtor && !dtor->isVirtual()) {
2382 if (PointeeRD->isAbstract()) {
2383 // If the class is abstract, we warn by default, because we're
2384 // sure the code has undefined behavior.
2385 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2387 } else if (!ArrayForm) {
2388 // Otherwise, if this is not an array delete, it's a bit suspect,
2389 // but not necessarily wrong.
2390 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2397 if (!OperatorDelete)
2398 // Look for a global declaration.
2399 OperatorDelete = FindUsualDeallocationFunction(
2400 StartLoc, !RequireCompleteType(StartLoc, Pointee, 0) &&
2401 (!ArrayForm || UsualArrayDeleteWantsSize ||
2402 Pointee.isDestructedType()),
2405 MarkFunctionReferenced(StartLoc, OperatorDelete);
2407 // Check access and ambiguity of operator delete and destructor.
2409 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2410 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
2411 PDiag(diag::err_access_dtor) << PointeeElem);
2416 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
2418 UsualArrayDeleteWantsSize,
2419 OperatorDelete, Ex.take(), StartLoc));
2422 /// \brief Check the use of the given variable as a C++ condition in an if,
2423 /// while, do-while, or switch statement.
2424 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
2425 SourceLocation StmtLoc,
2426 bool ConvertToBoolean) {
2427 if (ConditionVar->isInvalidDecl())
2430 QualType T = ConditionVar->getType();
2432 // C++ [stmt.select]p2:
2433 // The declarator shall not specify a function or an array.
2434 if (T->isFunctionType())
2435 return ExprError(Diag(ConditionVar->getLocation(),
2436 diag::err_invalid_use_of_function_type)
2437 << ConditionVar->getSourceRange());
2438 else if (T->isArrayType())
2439 return ExprError(Diag(ConditionVar->getLocation(),
2440 diag::err_invalid_use_of_array_type)
2441 << ConditionVar->getSourceRange());
2443 ExprResult Condition =
2444 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2447 /*enclosing*/ false,
2448 ConditionVar->getLocation(),
2449 ConditionVar->getType().getNonReferenceType(),
2452 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
2454 if (ConvertToBoolean) {
2455 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2456 if (Condition.isInvalid())
2463 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
2464 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
2466 // The value of a condition that is an initialized declaration in a statement
2467 // other than a switch statement is the value of the declared variable
2468 // implicitly converted to type bool. If that conversion is ill-formed, the
2469 // program is ill-formed.
2470 // The value of a condition that is an expression is the value of the
2471 // expression, implicitly converted to bool.
2473 return PerformContextuallyConvertToBool(CondExpr);
2476 /// Helper function to determine whether this is the (deprecated) C++
2477 /// conversion from a string literal to a pointer to non-const char or
2478 /// non-const wchar_t (for narrow and wide string literals,
2481 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2482 // Look inside the implicit cast, if it exists.
2483 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2484 From = Cast->getSubExpr();
2486 // A string literal (2.13.4) that is not a wide string literal can
2487 // be converted to an rvalue of type "pointer to char"; a wide
2488 // string literal can be converted to an rvalue of type "pointer
2489 // to wchar_t" (C++ 4.2p2).
2490 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
2491 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
2492 if (const BuiltinType *ToPointeeType
2493 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
2494 // This conversion is considered only when there is an
2495 // explicit appropriate pointer target type (C++ 4.2p2).
2496 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2497 switch (StrLit->getKind()) {
2498 case StringLiteral::UTF8:
2499 case StringLiteral::UTF16:
2500 case StringLiteral::UTF32:
2501 // We don't allow UTF literals to be implicitly converted
2503 case StringLiteral::Ascii:
2504 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2505 ToPointeeType->getKind() == BuiltinType::Char_S);
2506 case StringLiteral::Wide:
2507 return ToPointeeType->isWideCharType();
2515 static ExprResult BuildCXXCastArgument(Sema &S,
2516 SourceLocation CastLoc,
2519 CXXMethodDecl *Method,
2520 DeclAccessPair FoundDecl,
2521 bool HadMultipleCandidates,
2524 default: llvm_unreachable("Unhandled cast kind!");
2525 case CK_ConstructorConversion: {
2526 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
2527 SmallVector<Expr*, 8> ConstructorArgs;
2529 if (S.RequireNonAbstractType(CastLoc, Ty,
2530 diag::err_allocation_of_abstract_type))
2533 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
2536 S.CheckConstructorAccess(CastLoc, Constructor,
2537 InitializedEntity::InitializeTemporary(Ty),
2538 Constructor->getAccess());
2541 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2542 ConstructorArgs, HadMultipleCandidates,
2543 /*ListInit*/ false, /*ZeroInit*/ false,
2544 CXXConstructExpr::CK_Complete, SourceRange());
2545 if (Result.isInvalid())
2548 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2551 case CK_UserDefinedConversion: {
2552 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2554 // Create an implicit call expr that calls it.
2555 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2556 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
2557 HadMultipleCandidates);
2558 if (Result.isInvalid())
2560 // Record usage of conversion in an implicit cast.
2561 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2562 Result.get()->getType(),
2563 CK_UserDefinedConversion,
2565 Result.get()->getValueKind()));
2567 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2569 return S.MaybeBindToTemporary(Result.get());
2574 /// PerformImplicitConversion - Perform an implicit conversion of the
2575 /// expression From to the type ToType using the pre-computed implicit
2576 /// conversion sequence ICS. Returns the converted
2577 /// expression. Action is the kind of conversion we're performing,
2578 /// used in the error message.
2580 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2581 const ImplicitConversionSequence &ICS,
2582 AssignmentAction Action,
2583 CheckedConversionKind CCK) {
2584 switch (ICS.getKind()) {
2585 case ImplicitConversionSequence::StandardConversion: {
2586 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2588 if (Res.isInvalid())
2594 case ImplicitConversionSequence::UserDefinedConversion: {
2596 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
2598 QualType BeforeToType;
2599 assert(FD && "FIXME: aggregate initialization from init list");
2600 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
2601 CastKind = CK_UserDefinedConversion;
2603 // If the user-defined conversion is specified by a conversion function,
2604 // the initial standard conversion sequence converts the source type to
2605 // the implicit object parameter of the conversion function.
2606 BeforeToType = Context.getTagDeclType(Conv->getParent());
2608 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
2609 CastKind = CK_ConstructorConversion;
2610 // Do no conversion if dealing with ... for the first conversion.
2611 if (!ICS.UserDefined.EllipsisConversion) {
2612 // If the user-defined conversion is specified by a constructor, the
2613 // initial standard conversion sequence converts the source type to the
2614 // type required by the argument of the constructor
2615 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2618 // Watch out for ellipsis conversion.
2619 if (!ICS.UserDefined.EllipsisConversion) {
2621 PerformImplicitConversion(From, BeforeToType,
2622 ICS.UserDefined.Before, AA_Converting,
2624 if (Res.isInvalid())
2630 = BuildCXXCastArgument(*this,
2631 From->getLocStart(),
2632 ToType.getNonReferenceType(),
2633 CastKind, cast<CXXMethodDecl>(FD),
2634 ICS.UserDefined.FoundConversionFunction,
2635 ICS.UserDefined.HadMultipleCandidates,
2638 if (CastArg.isInvalid())
2641 From = CastArg.take();
2643 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2644 AA_Converting, CCK);
2647 case ImplicitConversionSequence::AmbiguousConversion:
2648 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2649 PDiag(diag::err_typecheck_ambiguous_condition)
2650 << From->getSourceRange());
2653 case ImplicitConversionSequence::EllipsisConversion:
2654 llvm_unreachable("Cannot perform an ellipsis conversion");
2656 case ImplicitConversionSequence::BadConversion:
2660 // Everything went well.
2664 /// PerformImplicitConversion - Perform an implicit conversion of the
2665 /// expression From to the type ToType by following the standard
2666 /// conversion sequence SCS. Returns the converted
2667 /// expression. Flavor is the context in which we're performing this
2668 /// conversion, for use in error messages.
2670 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2671 const StandardConversionSequence& SCS,
2672 AssignmentAction Action,
2673 CheckedConversionKind CCK) {
2674 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2676 // Overall FIXME: we are recomputing too many types here and doing far too
2677 // much extra work. What this means is that we need to keep track of more
2678 // information that is computed when we try the implicit conversion initially,
2679 // so that we don't need to recompute anything here.
2680 QualType FromType = From->getType();
2682 if (SCS.CopyConstructor) {
2683 // FIXME: When can ToType be a reference type?
2684 assert(!ToType->isReferenceType());
2685 if (SCS.Second == ICK_Derived_To_Base) {
2686 SmallVector<Expr*, 8> ConstructorArgs;
2687 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2688 From, /*FIXME:ConstructLoc*/SourceLocation(),
2691 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2692 ToType, SCS.CopyConstructor,
2694 /*HadMultipleCandidates*/ false,
2695 /*ListInit*/ false, /*ZeroInit*/ false,
2696 CXXConstructExpr::CK_Complete,
2699 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2700 ToType, SCS.CopyConstructor,
2701 From, /*HadMultipleCandidates*/ false,
2702 /*ListInit*/ false, /*ZeroInit*/ false,
2703 CXXConstructExpr::CK_Complete,
2707 // Resolve overloaded function references.
2708 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2709 DeclAccessPair Found;
2710 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2715 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
2718 From = FixOverloadedFunctionReference(From, Found, Fn);
2719 FromType = From->getType();
2722 // If we're converting to an atomic type, first convert to the corresponding
2724 QualType ToAtomicType;
2725 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
2726 ToAtomicType = ToType;
2727 ToType = ToAtomic->getValueType();
2730 // Perform the first implicit conversion.
2731 switch (SCS.First) {
2736 case ICK_Lvalue_To_Rvalue: {
2737 assert(From->getObjectKind() != OK_ObjCProperty);
2738 FromType = FromType.getUnqualifiedType();
2739 ExprResult FromRes = DefaultLvalueConversion(From);
2740 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2741 From = FromRes.take();
2745 case ICK_Array_To_Pointer:
2746 FromType = Context.getArrayDecayedType(FromType);
2747 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2748 VK_RValue, /*BasePath=*/0, CCK).take();
2751 case ICK_Function_To_Pointer:
2752 FromType = Context.getPointerType(FromType);
2753 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2754 VK_RValue, /*BasePath=*/0, CCK).take();
2758 llvm_unreachable("Improper first standard conversion");
2761 // Perform the second implicit conversion
2762 switch (SCS.Second) {
2764 // If both sides are functions (or pointers/references to them), there could
2765 // be incompatible exception declarations.
2766 if (CheckExceptionSpecCompatibility(From, ToType))
2768 // Nothing else to do.
2771 case ICK_NoReturn_Adjustment:
2772 // If both sides are functions (or pointers/references to them), there could
2773 // be incompatible exception declarations.
2774 if (CheckExceptionSpecCompatibility(From, ToType))
2777 From = ImpCastExprToType(From, ToType, CK_NoOp,
2778 VK_RValue, /*BasePath=*/0, CCK).take();
2781 case ICK_Integral_Promotion:
2782 case ICK_Integral_Conversion:
2783 if (ToType->isBooleanType()) {
2784 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
2785 SCS.Second == ICK_Integral_Promotion &&
2786 "only enums with fixed underlying type can promote to bool");
2787 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
2788 VK_RValue, /*BasePath=*/0, CCK).take();
2790 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2791 VK_RValue, /*BasePath=*/0, CCK).take();
2795 case ICK_Floating_Promotion:
2796 case ICK_Floating_Conversion:
2797 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2798 VK_RValue, /*BasePath=*/0, CCK).take();
2801 case ICK_Complex_Promotion:
2802 case ICK_Complex_Conversion: {
2803 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2804 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2806 if (FromEl->isRealFloatingType()) {
2807 if (ToEl->isRealFloatingType())
2808 CK = CK_FloatingComplexCast;
2810 CK = CK_FloatingComplexToIntegralComplex;
2811 } else if (ToEl->isRealFloatingType()) {
2812 CK = CK_IntegralComplexToFloatingComplex;
2814 CK = CK_IntegralComplexCast;
2816 From = ImpCastExprToType(From, ToType, CK,
2817 VK_RValue, /*BasePath=*/0, CCK).take();
2821 case ICK_Floating_Integral:
2822 if (ToType->isRealFloatingType())
2823 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2824 VK_RValue, /*BasePath=*/0, CCK).take();
2826 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2827 VK_RValue, /*BasePath=*/0, CCK).take();
2830 case ICK_Compatible_Conversion:
2831 From = ImpCastExprToType(From, ToType, CK_NoOp,
2832 VK_RValue, /*BasePath=*/0, CCK).take();
2835 case ICK_Writeback_Conversion:
2836 case ICK_Pointer_Conversion: {
2837 if (SCS.IncompatibleObjC && Action != AA_Casting) {
2838 // Diagnose incompatible Objective-C conversions
2839 if (Action == AA_Initializing || Action == AA_Assigning)
2840 Diag(From->getLocStart(),
2841 diag::ext_typecheck_convert_incompatible_pointer)
2842 << ToType << From->getType() << Action
2843 << From->getSourceRange() << 0;
2845 Diag(From->getLocStart(),
2846 diag::ext_typecheck_convert_incompatible_pointer)
2847 << From->getType() << ToType << Action
2848 << From->getSourceRange() << 0;
2850 if (From->getType()->isObjCObjectPointerType() &&
2851 ToType->isObjCObjectPointerType())
2852 EmitRelatedResultTypeNote(From);
2854 else if (getLangOpts().ObjCAutoRefCount &&
2855 !CheckObjCARCUnavailableWeakConversion(ToType,
2857 if (Action == AA_Initializing)
2858 Diag(From->getLocStart(),
2859 diag::err_arc_weak_unavailable_assign);
2861 Diag(From->getLocStart(),
2862 diag::err_arc_convesion_of_weak_unavailable)
2863 << (Action == AA_Casting) << From->getType() << ToType
2864 << From->getSourceRange();
2867 CastKind Kind = CK_Invalid;
2868 CXXCastPath BasePath;
2869 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2872 // Make sure we extend blocks if necessary.
2873 // FIXME: doing this here is really ugly.
2874 if (Kind == CK_BlockPointerToObjCPointerCast) {
2875 ExprResult E = From;
2876 (void) PrepareCastToObjCObjectPointer(E);
2879 if (getLangOpts().ObjCAutoRefCount)
2880 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
2881 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2886 case ICK_Pointer_Member: {
2887 CastKind Kind = CK_Invalid;
2888 CXXCastPath BasePath;
2889 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2891 if (CheckExceptionSpecCompatibility(From, ToType))
2893 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2898 case ICK_Boolean_Conversion:
2899 // Perform half-to-boolean conversion via float.
2900 if (From->getType()->isHalfType()) {
2901 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2902 FromType = Context.FloatTy;
2905 From = ImpCastExprToType(From, Context.BoolTy,
2906 ScalarTypeToBooleanCastKind(FromType),
2907 VK_RValue, /*BasePath=*/0, CCK).take();
2910 case ICK_Derived_To_Base: {
2911 CXXCastPath BasePath;
2912 if (CheckDerivedToBaseConversion(From->getType(),
2913 ToType.getNonReferenceType(),
2914 From->getLocStart(),
2915 From->getSourceRange(),
2920 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2921 CK_DerivedToBase, From->getValueKind(),
2922 &BasePath, CCK).take();
2926 case ICK_Vector_Conversion:
2927 From = ImpCastExprToType(From, ToType, CK_BitCast,
2928 VK_RValue, /*BasePath=*/0, CCK).take();
2931 case ICK_Vector_Splat:
2932 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2933 VK_RValue, /*BasePath=*/0, CCK).take();
2936 case ICK_Complex_Real:
2937 // Case 1. x -> _Complex y
2938 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2939 QualType ElType = ToComplex->getElementType();
2940 bool isFloatingComplex = ElType->isRealFloatingType();
2943 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2945 } else if (From->getType()->isRealFloatingType()) {
2946 From = ImpCastExprToType(From, ElType,
2947 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
2949 assert(From->getType()->isIntegerType());
2950 From = ImpCastExprToType(From, ElType,
2951 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
2954 From = ImpCastExprToType(From, ToType,
2955 isFloatingComplex ? CK_FloatingRealToComplex
2956 : CK_IntegralRealToComplex).take();
2958 // Case 2. _Complex x -> y
2960 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2961 assert(FromComplex);
2963 QualType ElType = FromComplex->getElementType();
2964 bool isFloatingComplex = ElType->isRealFloatingType();
2967 From = ImpCastExprToType(From, ElType,
2968 isFloatingComplex ? CK_FloatingComplexToReal
2969 : CK_IntegralComplexToReal,
2970 VK_RValue, /*BasePath=*/0, CCK).take();
2973 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2975 } else if (ToType->isRealFloatingType()) {
2976 From = ImpCastExprToType(From, ToType,
2977 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2978 VK_RValue, /*BasePath=*/0, CCK).take();
2980 assert(ToType->isIntegerType());
2981 From = ImpCastExprToType(From, ToType,
2982 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2983 VK_RValue, /*BasePath=*/0, CCK).take();
2988 case ICK_Block_Pointer_Conversion: {
2989 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2990 VK_RValue, /*BasePath=*/0, CCK).take();
2994 case ICK_TransparentUnionConversion: {
2995 ExprResult FromRes = Owned(From);
2996 Sema::AssignConvertType ConvTy =
2997 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2998 if (FromRes.isInvalid())
3000 From = FromRes.take();
3001 assert ((ConvTy == Sema::Compatible) &&
3002 "Improper transparent union conversion");
3007 case ICK_Zero_Event_Conversion:
3008 From = ImpCastExprToType(From, ToType,
3010 From->getValueKind()).take();
3013 case ICK_Lvalue_To_Rvalue:
3014 case ICK_Array_To_Pointer:
3015 case ICK_Function_To_Pointer:
3016 case ICK_Qualification:
3017 case ICK_Num_Conversion_Kinds:
3018 llvm_unreachable("Improper second standard conversion");
3021 switch (SCS.Third) {
3026 case ICK_Qualification: {
3027 // The qualification keeps the category of the inner expression, unless the
3028 // target type isn't a reference.
3029 ExprValueKind VK = ToType->isReferenceType() ?
3030 From->getValueKind() : VK_RValue;
3031 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
3032 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
3034 if (SCS.DeprecatedStringLiteralToCharPtr &&
3035 !getLangOpts().WritableStrings)
3036 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
3037 << ToType.getNonReferenceType();
3043 llvm_unreachable("Improper third standard conversion");
3046 // If this conversion sequence involved a scalar -> atomic conversion, perform
3047 // that conversion now.
3048 if (!ToAtomicType.isNull()) {
3049 assert(Context.hasSameType(
3050 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3051 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
3052 VK_RValue, 0, CCK).take();
3058 ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
3059 SourceLocation KWLoc,
3061 SourceLocation RParen) {
3062 TypeSourceInfo *TSInfo;
3063 QualType T = GetTypeFromParser(Ty, &TSInfo);
3066 TSInfo = Context.getTrivialTypeSourceInfo(T);
3067 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
3070 /// \brief Check the completeness of a type in a unary type trait.
3072 /// If the particular type trait requires a complete type, tries to complete
3073 /// it. If completing the type fails, a diagnostic is emitted and false
3074 /// returned. If completing the type succeeds or no completion was required,
3076 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
3080 // C++0x [meta.unary.prop]p3:
3081 // For all of the class templates X declared in this Clause, instantiating
3082 // that template with a template argument that is a class template
3083 // specialization may result in the implicit instantiation of the template
3084 // argument if and only if the semantics of X require that the argument
3085 // must be a complete type.
3086 // We apply this rule to all the type trait expressions used to implement
3087 // these class templates. We also try to follow any GCC documented behavior
3088 // in these expressions to ensure portability of standard libraries.
3090 // is_complete_type somewhat obviously cannot require a complete type.
3091 case UTT_IsCompleteType:
3094 // These traits are modeled on the type predicates in C++0x
3095 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3096 // requiring a complete type, as whether or not they return true cannot be
3097 // impacted by the completeness of the type.
3099 case UTT_IsIntegral:
3100 case UTT_IsFloatingPoint:
3103 case UTT_IsLvalueReference:
3104 case UTT_IsRvalueReference:
3105 case UTT_IsMemberFunctionPointer:
3106 case UTT_IsMemberObjectPointer:
3110 case UTT_IsFunction:
3111 case UTT_IsReference:
3112 case UTT_IsArithmetic:
3113 case UTT_IsFundamental:
3116 case UTT_IsCompound:
3117 case UTT_IsMemberPointer:
3120 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3121 // which requires some of its traits to have the complete type. However,
3122 // the completeness of the type cannot impact these traits' semantics, and
3123 // so they don't require it. This matches the comments on these traits in
3126 case UTT_IsVolatile:
3128 case UTT_IsUnsigned:
3131 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
3132 // applied to a complete type.
3134 case UTT_IsTriviallyCopyable:
3135 case UTT_IsStandardLayout:
3139 case UTT_IsPolymorphic:
3140 case UTT_IsAbstract:
3141 case UTT_IsInterfaceClass:
3144 // These traits require a complete type.
3148 // These trait expressions are designed to help implement predicates in
3149 // [meta.unary.prop] despite not being named the same. They are specified
3150 // by both GCC and the Embarcadero C++ compiler, and require the complete
3151 // type due to the overarching C++0x type predicates being implemented
3152 // requiring the complete type.
3153 case UTT_HasNothrowAssign:
3154 case UTT_HasNothrowMoveAssign:
3155 case UTT_HasNothrowConstructor:
3156 case UTT_HasNothrowCopy:
3157 case UTT_HasTrivialAssign:
3158 case UTT_HasTrivialMoveAssign:
3159 case UTT_HasTrivialDefaultConstructor:
3160 case UTT_HasTrivialMoveConstructor:
3161 case UTT_HasTrivialCopy:
3162 case UTT_HasTrivialDestructor:
3163 case UTT_HasVirtualDestructor:
3164 // Arrays of unknown bound are expressly allowed.
3165 QualType ElTy = ArgTy;
3166 if (ArgTy->isIncompleteArrayType())
3167 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
3169 // The void type is expressly allowed.
3170 if (ElTy->isVoidType())
3173 return !S.RequireCompleteType(
3174 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
3176 llvm_unreachable("Type trait not handled by switch");
3179 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
3180 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
3181 bool (CXXRecordDecl::*HasTrivial)() const,
3182 bool (CXXRecordDecl::*HasNonTrivial)() const,
3183 bool (CXXMethodDecl::*IsDesiredOp)() const)
3185 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3186 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
3189 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
3190 DeclarationNameInfo NameInfo(Name, KeyLoc);
3191 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
3192 if (Self.LookupQualifiedName(Res, RD)) {
3193 bool FoundOperator = false;
3194 Res.suppressDiagnostics();
3195 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3196 Op != OpEnd; ++Op) {
3197 if (isa<FunctionTemplateDecl>(*Op))
3200 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3201 if((Operator->*IsDesiredOp)()) {
3202 FoundOperator = true;
3203 const FunctionProtoType *CPT =
3204 Operator->getType()->getAs<FunctionProtoType>();
3205 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3206 if (!CPT || !CPT->isNothrow(Self.Context))
3210 return FoundOperator;
3215 static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
3216 SourceLocation KeyLoc, QualType T) {
3217 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3219 ASTContext &C = Self.Context;
3221 // Type trait expressions corresponding to the primary type category
3222 // predicates in C++0x [meta.unary.cat].
3224 return T->isVoidType();
3225 case UTT_IsIntegral:
3226 return T->isIntegralType(C);
3227 case UTT_IsFloatingPoint:
3228 return T->isFloatingType();
3230 return T->isArrayType();
3232 return T->isPointerType();
3233 case UTT_IsLvalueReference:
3234 return T->isLValueReferenceType();
3235 case UTT_IsRvalueReference:
3236 return T->isRValueReferenceType();
3237 case UTT_IsMemberFunctionPointer:
3238 return T->isMemberFunctionPointerType();
3239 case UTT_IsMemberObjectPointer:
3240 return T->isMemberDataPointerType();
3242 return T->isEnumeralType();
3244 return T->isUnionType();
3246 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
3247 case UTT_IsFunction:
3248 return T->isFunctionType();
3250 // Type trait expressions which correspond to the convenient composition
3251 // predicates in C++0x [meta.unary.comp].
3252 case UTT_IsReference:
3253 return T->isReferenceType();
3254 case UTT_IsArithmetic:
3255 return T->isArithmeticType() && !T->isEnumeralType();
3256 case UTT_IsFundamental:
3257 return T->isFundamentalType();
3259 return T->isObjectType();
3261 // Note: semantic analysis depends on Objective-C lifetime types to be
3262 // considered scalar types. However, such types do not actually behave
3263 // like scalar types at run time (since they may require retain/release
3264 // operations), so we report them as non-scalar.
3265 if (T->isObjCLifetimeType()) {
3266 switch (T.getObjCLifetime()) {
3267 case Qualifiers::OCL_None:
3268 case Qualifiers::OCL_ExplicitNone:
3271 case Qualifiers::OCL_Strong:
3272 case Qualifiers::OCL_Weak:
3273 case Qualifiers::OCL_Autoreleasing:
3278 return T->isScalarType();
3279 case UTT_IsCompound:
3280 return T->isCompoundType();
3281 case UTT_IsMemberPointer:
3282 return T->isMemberPointerType();
3284 // Type trait expressions which correspond to the type property predicates
3285 // in C++0x [meta.unary.prop].
3287 return T.isConstQualified();
3288 case UTT_IsVolatile:
3289 return T.isVolatileQualified();
3291 return T.isTrivialType(Self.Context);
3292 case UTT_IsTriviallyCopyable:
3293 return T.isTriviallyCopyableType(Self.Context);
3294 case UTT_IsStandardLayout:
3295 return T->isStandardLayoutType();
3297 return T.isPODType(Self.Context);
3299 return T->isLiteralType(Self.Context);
3301 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3302 return !RD->isUnion() && RD->isEmpty();
3304 case UTT_IsPolymorphic:
3305 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3306 return RD->isPolymorphic();
3308 case UTT_IsAbstract:
3309 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3310 return RD->isAbstract();
3312 case UTT_IsInterfaceClass:
3313 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3314 return RD->isInterface();
3317 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3318 return RD->hasAttr<FinalAttr>();
3321 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3322 if (FinalAttr *FA = RD->getAttr<FinalAttr>())
3323 return FA->isSpelledAsSealed();
3326 return T->isSignedIntegerType();
3327 case UTT_IsUnsigned:
3328 return T->isUnsignedIntegerType();
3330 // Type trait expressions which query classes regarding their construction,
3331 // destruction, and copying. Rather than being based directly on the
3332 // related type predicates in the standard, they are specified by both
3333 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3336 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3337 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3339 // Note that these builtins do not behave as documented in g++: if a class
3340 // has both a trivial and a non-trivial special member of a particular kind,
3341 // they return false! For now, we emulate this behavior.
3342 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
3343 // does not correctly compute triviality in the presence of multiple special
3344 // members of the same kind. Revisit this once the g++ bug is fixed.
3345 case UTT_HasTrivialDefaultConstructor:
3346 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3347 // If __is_pod (type) is true then the trait is true, else if type is
3348 // a cv class or union type (or array thereof) with a trivial default
3349 // constructor ([class.ctor]) then the trait is true, else it is false.
3350 if (T.isPODType(Self.Context))
3352 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3353 return RD->hasTrivialDefaultConstructor() &&
3354 !RD->hasNonTrivialDefaultConstructor();
3356 case UTT_HasTrivialMoveConstructor:
3357 // This trait is implemented by MSVC 2012 and needed to parse the
3358 // standard library headers. Specifically this is used as the logic
3359 // behind std::is_trivially_move_constructible (20.9.4.3).
3360 if (T.isPODType(Self.Context))
3362 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3363 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
3365 case UTT_HasTrivialCopy:
3366 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3367 // If __is_pod (type) is true or type is a reference type then
3368 // the trait is true, else if type is a cv class or union type
3369 // with a trivial copy constructor ([class.copy]) then the trait
3370 // is true, else it is false.
3371 if (T.isPODType(Self.Context) || T->isReferenceType())
3373 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3374 return RD->hasTrivialCopyConstructor() &&
3375 !RD->hasNonTrivialCopyConstructor();
3377 case UTT_HasTrivialMoveAssign:
3378 // This trait is implemented by MSVC 2012 and needed to parse the
3379 // standard library headers. Specifically it is used as the logic
3380 // behind std::is_trivially_move_assignable (20.9.4.3)
3381 if (T.isPODType(Self.Context))
3383 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3384 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
3386 case UTT_HasTrivialAssign:
3387 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3388 // If type is const qualified or is a reference type then the
3389 // trait is false. Otherwise if __is_pod (type) is true then the
3390 // trait is true, else if type is a cv class or union type with
3391 // a trivial copy assignment ([class.copy]) then the trait is
3392 // true, else it is false.
3393 // Note: the const and reference restrictions are interesting,
3394 // given that const and reference members don't prevent a class
3395 // from having a trivial copy assignment operator (but do cause
3396 // errors if the copy assignment operator is actually used, q.v.
3397 // [class.copy]p12).
3399 if (T.isConstQualified())
3401 if (T.isPODType(Self.Context))
3403 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3404 return RD->hasTrivialCopyAssignment() &&
3405 !RD->hasNonTrivialCopyAssignment();
3407 case UTT_HasTrivialDestructor:
3408 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3409 // If __is_pod (type) is true or type is a reference type
3410 // then the trait is true, else if type is a cv class or union
3411 // type (or array thereof) with a trivial destructor
3412 // ([class.dtor]) then the trait is true, else it is
3414 if (T.isPODType(Self.Context) || T->isReferenceType())
3417 // Objective-C++ ARC: autorelease types don't require destruction.
3418 if (T->isObjCLifetimeType() &&
3419 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3422 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3423 return RD->hasTrivialDestructor();
3425 // TODO: Propagate nothrowness for implicitly declared special members.
3426 case UTT_HasNothrowAssign:
3427 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3428 // If type is const qualified or is a reference type then the
3429 // trait is false. Otherwise if __has_trivial_assign (type)
3430 // is true then the trait is true, else if type is a cv class
3431 // or union type with copy assignment operators that are known
3432 // not to throw an exception then the trait is true, else it is
3434 if (C.getBaseElementType(T).isConstQualified())
3436 if (T->isReferenceType())
3438 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3441 if (const RecordType *RT = T->getAs<RecordType>())
3442 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3443 &CXXRecordDecl::hasTrivialCopyAssignment,
3444 &CXXRecordDecl::hasNonTrivialCopyAssignment,
3445 &CXXMethodDecl::isCopyAssignmentOperator);
3447 case UTT_HasNothrowMoveAssign:
3448 // This trait is implemented by MSVC 2012 and needed to parse the
3449 // standard library headers. Specifically this is used as the logic
3450 // behind std::is_nothrow_move_assignable (20.9.4.3).
3451 if (T.isPODType(Self.Context))
3454 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
3455 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3456 &CXXRecordDecl::hasTrivialMoveAssignment,
3457 &CXXRecordDecl::hasNonTrivialMoveAssignment,
3458 &CXXMethodDecl::isMoveAssignmentOperator);
3460 case UTT_HasNothrowCopy:
3461 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3462 // If __has_trivial_copy (type) is true then the trait is true, else
3463 // if type is a cv class or union type with copy constructors that are
3464 // known not to throw an exception then the trait is true, else it is
3466 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
3468 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
3469 if (RD->hasTrivialCopyConstructor() &&
3470 !RD->hasNonTrivialCopyConstructor())
3473 bool FoundConstructor = false;
3475 DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3476 for (DeclContext::lookup_const_iterator Con = R.begin(),
3477 ConEnd = R.end(); Con != ConEnd; ++Con) {
3478 // A template constructor is never a copy constructor.
3479 // FIXME: However, it may actually be selected at the actual overload
3480 // resolution point.
3481 if (isa<FunctionTemplateDecl>(*Con))
3483 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3484 if (Constructor->isCopyConstructor(FoundTQs)) {
3485 FoundConstructor = true;
3486 const FunctionProtoType *CPT
3487 = Constructor->getType()->getAs<FunctionProtoType>();
3488 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3491 // FIXME: check whether evaluating default arguments can throw.
3492 // For now, we'll be conservative and assume that they can throw.
3493 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3498 return FoundConstructor;
3501 case UTT_HasNothrowConstructor:
3502 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3503 // If __has_trivial_constructor (type) is true then the trait is
3504 // true, else if type is a cv class or union type (or array
3505 // thereof) with a default constructor that is known not to
3506 // throw an exception then the trait is true, else it is false.
3507 if (T.isPODType(C) || T->isObjCLifetimeType())
3509 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
3510 if (RD->hasTrivialDefaultConstructor() &&
3511 !RD->hasNonTrivialDefaultConstructor())
3514 DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3515 for (DeclContext::lookup_const_iterator Con = R.begin(),
3516 ConEnd = R.end(); Con != ConEnd; ++Con) {
3517 // FIXME: In C++0x, a constructor template can be a default constructor.
3518 if (isa<FunctionTemplateDecl>(*Con))
3520 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3521 if (Constructor->isDefaultConstructor()) {
3522 const FunctionProtoType *CPT
3523 = Constructor->getType()->getAs<FunctionProtoType>();
3524 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3527 // TODO: check whether evaluating default arguments can throw.
3528 // For now, we'll be conservative and assume that they can throw.
3529 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
3534 case UTT_HasVirtualDestructor:
3535 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3536 // If type is a class type with a virtual destructor ([class.dtor])
3537 // then the trait is true, else it is false.
3538 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3539 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
3540 return Destructor->isVirtual();
3543 // These type trait expressions are modeled on the specifications for the
3544 // Embarcadero C++0x type trait functions:
3545 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3546 case UTT_IsCompleteType:
3547 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3548 // Returns True if and only if T is a complete type at the point of the
3550 return !T->isIncompleteType();
3552 llvm_unreachable("Type trait not covered by switch");
3555 ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
3556 SourceLocation KWLoc,
3557 TypeSourceInfo *TSInfo,
3558 SourceLocation RParen) {
3559 QualType T = TSInfo->getType();
3560 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3564 if (!T->isDependentType())
3565 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
3567 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
3568 RParen, Context.BoolTy));
3571 ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3572 SourceLocation KWLoc,
3575 SourceLocation RParen) {
3576 TypeSourceInfo *LhsTSInfo;
3577 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3579 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3581 TypeSourceInfo *RhsTSInfo;
3582 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3584 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3586 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3589 /// \brief Determine whether T has a non-trivial Objective-C lifetime in
3591 static bool hasNontrivialObjCLifetime(QualType T) {
3592 switch (T.getObjCLifetime()) {
3593 case Qualifiers::OCL_ExplicitNone:
3596 case Qualifiers::OCL_Strong:
3597 case Qualifiers::OCL_Weak:
3598 case Qualifiers::OCL_Autoreleasing:
3601 case Qualifiers::OCL_None:
3602 return T->isObjCLifetimeType();
3605 llvm_unreachable("Unknown ObjC lifetime qualifier");
3608 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3609 ArrayRef<TypeSourceInfo *> Args,
3610 SourceLocation RParenLoc) {
3612 case clang::TT_IsTriviallyConstructible: {
3613 // C++11 [meta.unary.prop]:
3614 // is_trivially_constructible is defined as:
3616 // is_constructible<T, Args...>::value is true and the variable
3617 // definition for is_constructible, as defined below, is known to call
3618 // no operation that is not trivial.
3620 // The predicate condition for a template specialization
3621 // is_constructible<T, Args...> shall be satisfied if and only if the
3622 // following variable definition would be well-formed for some invented
3625 // T t(create<Args>()...);
3627 S.Diag(KWLoc, diag::err_type_trait_arity)
3628 << 1 << 1 << 1 << (int)Args.size();
3632 // Precondition: T and all types in the parameter pack Args shall be
3633 // complete types, (possibly cv-qualified) void, or arrays of
3635 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3636 QualType ArgTy = Args[I]->getType();
3637 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
3640 if (S.RequireCompleteType(KWLoc, ArgTy,
3641 diag::err_incomplete_type_used_in_type_trait_expr))
3645 // Make sure the first argument is a complete type.
3646 if (Args[0]->getType()->isIncompleteType())
3649 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3650 SmallVector<Expr *, 2> ArgExprs;
3651 ArgExprs.reserve(Args.size() - 1);
3652 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3653 QualType T = Args[I]->getType();
3654 if (T->isObjectType() || T->isFunctionType())
3655 T = S.Context.getRValueReferenceType(T);
3656 OpaqueArgExprs.push_back(
3657 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
3658 T.getNonLValueExprType(S.Context),
3659 Expr::getValueKindForType(T)));
3660 ArgExprs.push_back(&OpaqueArgExprs.back());
3663 // Perform the initialization in an unevaluated context within a SFINAE
3664 // trap at translation unit scope.
3665 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3666 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3667 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3668 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3669 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3671 InitializationSequence Init(S, To, InitKind, ArgExprs);
3675 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
3676 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3679 // Under Objective-C ARC, if the destination has non-trivial Objective-C
3680 // lifetime, this is a non-trivial construction.
3681 if (S.getLangOpts().ObjCAutoRefCount &&
3682 hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType()))
3685 // The initialization succeeded; now make sure there are no non-trivial
3687 return !Result.get()->hasNonTrivialCall(S.Context);
3694 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3695 ArrayRef<TypeSourceInfo *> Args,
3696 SourceLocation RParenLoc) {
3697 bool Dependent = false;
3698 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3699 if (Args[I]->getType()->isDependentType()) {
3707 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3709 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3710 Args, RParenLoc, Value);
3713 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3714 ArrayRef<ParsedType> Args,
3715 SourceLocation RParenLoc) {
3716 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3717 ConvertedArgs.reserve(Args.size());
3719 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3720 TypeSourceInfo *TInfo;
3721 QualType T = GetTypeFromParser(Args[I], &TInfo);
3723 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3725 ConvertedArgs.push_back(TInfo);
3728 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3731 static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3732 QualType LhsT, QualType RhsT,
3733 SourceLocation KeyLoc) {
3734 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3735 "Cannot evaluate traits of dependent types");
3738 case BTT_IsBaseOf: {
3739 // C++0x [meta.rel]p2
3740 // Base is a base class of Derived without regard to cv-qualifiers or
3741 // Base and Derived are not unions and name the same class type without
3742 // regard to cv-qualifiers.
3744 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3745 if (!lhsRecord) return false;
3747 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3748 if (!rhsRecord) return false;
3750 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3751 == (lhsRecord == rhsRecord));
3753 if (lhsRecord == rhsRecord)
3754 return !lhsRecord->getDecl()->isUnion();
3756 // C++0x [meta.rel]p2:
3757 // If Base and Derived are class types and are different types
3758 // (ignoring possible cv-qualifiers) then Derived shall be a
3760 if (Self.RequireCompleteType(KeyLoc, RhsT,
3761 diag::err_incomplete_type_used_in_type_trait_expr))
3764 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3765 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3768 return Self.Context.hasSameType(LhsT, RhsT);
3769 case BTT_TypeCompatible:
3770 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3771 RhsT.getUnqualifiedType());
3772 case BTT_IsConvertible:
3773 case BTT_IsConvertibleTo: {
3774 // C++0x [meta.rel]p4:
3775 // Given the following function prototype:
3777 // template <class T>
3778 // typename add_rvalue_reference<T>::type create();
3780 // the predicate condition for a template specialization
3781 // is_convertible<From, To> shall be satisfied if and only if
3782 // the return expression in the following code would be
3783 // well-formed, including any implicit conversions to the return
3784 // type of the function:
3787 // return create<From>();
3790 // Access checking is performed as if in a context unrelated to To and
3791 // From. Only the validity of the immediate context of the expression
3792 // of the return-statement (including conversions to the return type)
3795 // We model the initialization as a copy-initialization of a temporary
3796 // of the appropriate type, which for this expression is identical to the
3797 // return statement (since NRVO doesn't apply).
3799 // Functions aren't allowed to return function or array types.
3800 if (RhsT->isFunctionType() || RhsT->isArrayType())
3803 // A return statement in a void function must have void type.
3804 if (RhsT->isVoidType())
3805 return LhsT->isVoidType();
3807 // A function definition requires a complete, non-abstract return type.
3808 if (Self.RequireCompleteType(KeyLoc, RhsT, 0) ||
3809 Self.RequireNonAbstractType(KeyLoc, RhsT, 0))
3812 // Compute the result of add_rvalue_reference.
3813 if (LhsT->isObjectType() || LhsT->isFunctionType())
3814 LhsT = Self.Context.getRValueReferenceType(LhsT);
3816 // Build a fake source and destination for initialization.
3817 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
3818 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3819 Expr::getValueKindForType(LhsT));
3820 Expr *FromPtr = &From;
3821 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3824 // Perform the initialization in an unevaluated context within a SFINAE
3825 // trap at translation unit scope.
3826 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3827 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3828 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3829 InitializationSequence Init(Self, To, Kind, FromPtr);
3833 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
3834 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3837 case BTT_IsTriviallyAssignable: {
3838 // C++11 [meta.unary.prop]p3:
3839 // is_trivially_assignable is defined as:
3840 // is_assignable<T, U>::value is true and the assignment, as defined by
3841 // is_assignable, is known to call no operation that is not trivial
3843 // is_assignable is defined as:
3844 // The expression declval<T>() = declval<U>() is well-formed when
3845 // treated as an unevaluated operand (Clause 5).
3847 // For both, T and U shall be complete types, (possibly cv-qualified)
3848 // void, or arrays of unknown bound.
3849 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3850 Self.RequireCompleteType(KeyLoc, LhsT,
3851 diag::err_incomplete_type_used_in_type_trait_expr))
3853 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3854 Self.RequireCompleteType(KeyLoc, RhsT,
3855 diag::err_incomplete_type_used_in_type_trait_expr))
3858 // cv void is never assignable.
3859 if (LhsT->isVoidType() || RhsT->isVoidType())
3862 // Build expressions that emulate the effect of declval<T>() and
3864 if (LhsT->isObjectType() || LhsT->isFunctionType())
3865 LhsT = Self.Context.getRValueReferenceType(LhsT);
3866 if (RhsT->isObjectType() || RhsT->isFunctionType())
3867 RhsT = Self.Context.getRValueReferenceType(RhsT);
3868 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3869 Expr::getValueKindForType(LhsT));
3870 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3871 Expr::getValueKindForType(RhsT));
3873 // Attempt the assignment in an unevaluated context within a SFINAE
3874 // trap at translation unit scope.
3875 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3876 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3877 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3878 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3879 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3882 // Under Objective-C ARC, if the destination has non-trivial Objective-C
3883 // lifetime, this is a non-trivial assignment.
3884 if (Self.getLangOpts().ObjCAutoRefCount &&
3885 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
3888 return !Result.get()->hasNonTrivialCall(Self.Context);
3891 llvm_unreachable("Unknown type trait or not implemented");
3894 ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3895 SourceLocation KWLoc,
3896 TypeSourceInfo *LhsTSInfo,
3897 TypeSourceInfo *RhsTSInfo,
3898 SourceLocation RParen) {
3899 QualType LhsT = LhsTSInfo->getType();
3900 QualType RhsT = RhsTSInfo->getType();
3902 if (BTT == BTT_TypeCompatible) {
3903 if (getLangOpts().CPlusPlus) {
3904 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3905 << SourceRange(KWLoc, RParen);
3911 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3912 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3914 // Select trait result type.
3915 QualType ResultType;
3917 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
3918 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3919 case BTT_IsSame: ResultType = Context.BoolTy; break;
3920 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
3921 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
3922 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
3925 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3926 RhsTSInfo, Value, RParen,
3930 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3931 SourceLocation KWLoc,
3934 SourceLocation RParen) {
3935 TypeSourceInfo *TSInfo;
3936 QualType T = GetTypeFromParser(Ty, &TSInfo);
3938 TSInfo = Context.getTrivialTypeSourceInfo(T);
3940 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3943 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3944 QualType T, Expr *DimExpr,
3945 SourceLocation KeyLoc) {
3946 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3950 if (T->isArrayType()) {
3952 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3954 T = AT->getElementType();
3960 case ATT_ArrayExtent: {
3963 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3964 diag::err_dimension_expr_not_constant_integer,
3967 if (Value.isSigned() && Value.isNegative()) {
3968 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3969 << DimExpr->getSourceRange();
3972 Dim = Value.getLimitedValue();
3974 if (T->isArrayType()) {
3976 bool Matched = false;
3977 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3983 T = AT->getElementType();
3986 if (Matched && T->isArrayType()) {
3987 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3988 return CAT->getSize().getLimitedValue();
3994 llvm_unreachable("Unknown type trait or not implemented");
3997 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3998 SourceLocation KWLoc,
3999 TypeSourceInfo *TSInfo,
4001 SourceLocation RParen) {
4002 QualType T = TSInfo->getType();
4004 // FIXME: This should likely be tracked as an APInt to remove any host
4005 // assumptions about the width of size_t on the target.
4007 if (!T->isDependentType())
4008 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4010 // While the specification for these traits from the Embarcadero C++
4011 // compiler's documentation says the return type is 'unsigned int', Clang
4012 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4013 // compiler, there is no difference. On several other platforms this is an
4014 // important distinction.
4015 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
4017 Context.getSizeType()));
4020 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
4021 SourceLocation KWLoc,
4023 SourceLocation RParen) {
4024 // If error parsing the expression, ignore.
4028 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
4033 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4035 case ET_IsLValueExpr: return E->isLValue();
4036 case ET_IsRValueExpr: return E->isRValue();
4038 llvm_unreachable("Expression trait not covered by switch");
4041 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
4042 SourceLocation KWLoc,
4044 SourceLocation RParen) {
4045 if (Queried->isTypeDependent()) {
4046 // Delay type-checking for type-dependent expressions.
4047 } else if (Queried->getType()->isPlaceholderType()) {
4048 ExprResult PE = CheckPlaceholderExpr(Queried);
4049 if (PE.isInvalid()) return ExprError();
4050 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
4053 bool Value = EvaluateExpressionTrait(ET, Queried);
4055 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
4056 RParen, Context.BoolTy));
4059 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
4063 assert(!LHS.get()->getType()->isPlaceholderType() &&
4064 !RHS.get()->getType()->isPlaceholderType() &&
4065 "placeholders should have been weeded out by now");
4067 // The LHS undergoes lvalue conversions if this is ->*.
4069 LHS = DefaultLvalueConversion(LHS.take());
4070 if (LHS.isInvalid()) return QualType();
4073 // The RHS always undergoes lvalue conversions.
4074 RHS = DefaultLvalueConversion(RHS.take());
4075 if (RHS.isInvalid()) return QualType();
4077 const char *OpSpelling = isIndirect ? "->*" : ".*";
4079 // The binary operator .* [p3: ->*] binds its second operand, which shall
4080 // be of type "pointer to member of T" (where T is a completely-defined
4081 // class type) [...]
4082 QualType RHSType = RHS.get()->getType();
4083 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
4085 Diag(Loc, diag::err_bad_memptr_rhs)
4086 << OpSpelling << RHSType << RHS.get()->getSourceRange();
4090 QualType Class(MemPtr->getClass(), 0);
4092 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4093 // member pointer points must be completely-defined. However, there is no
4094 // reason for this semantic distinction, and the rule is not enforced by
4095 // other compilers. Therefore, we do not check this property, as it is
4096 // likely to be considered a defect.
4099 // [...] to its first operand, which shall be of class T or of a class of
4100 // which T is an unambiguous and accessible base class. [p3: a pointer to
4102 QualType LHSType = LHS.get()->getType();
4104 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4105 LHSType = Ptr->getPointeeType();
4107 Diag(Loc, diag::err_bad_memptr_lhs)
4108 << OpSpelling << 1 << LHSType
4109 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
4114 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
4115 // If we want to check the hierarchy, we need a complete type.
4116 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
4117 OpSpelling, (int)isIndirect)) {
4120 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4121 /*DetectVirtual=*/false);
4122 // FIXME: Would it be useful to print full ambiguity paths, or is that
4124 if (!IsDerivedFrom(LHSType, Class, Paths) ||
4125 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
4126 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
4127 << (int)isIndirect << LHS.get()->getType();
4130 // Cast LHS to type of use.
4131 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
4132 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
4134 CXXCastPath BasePath;
4135 BuildBasePathArray(Paths, BasePath);
4136 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
4140 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
4141 // Diagnose use of pointer-to-member type which when used as
4142 // the functional cast in a pointer-to-member expression.
4143 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
4148 // The result is an object or a function of the type specified by the
4150 // The cv qualifiers are the union of those in the pointer and the left side,
4151 // in accordance with 5.5p5 and 5.2.5.
4152 QualType Result = MemPtr->getPointeeType();
4153 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
4155 // C++0x [expr.mptr.oper]p6:
4156 // In a .* expression whose object expression is an rvalue, the program is
4157 // ill-formed if the second operand is a pointer to member function with
4158 // ref-qualifier &. In a ->* expression or in a .* expression whose object
4159 // expression is an lvalue, the program is ill-formed if the second operand
4160 // is a pointer to member function with ref-qualifier &&.
4161 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
4162 switch (Proto->getRefQualifier()) {
4168 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
4169 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4170 << RHSType << 1 << LHS.get()->getSourceRange();
4174 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
4175 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4176 << RHSType << 0 << LHS.get()->getSourceRange();
4181 // C++ [expr.mptr.oper]p6:
4182 // The result of a .* expression whose second operand is a pointer
4183 // to a data member is of the same value category as its
4184 // first operand. The result of a .* expression whose second
4185 // operand is a pointer to a member function is a prvalue. The
4186 // result of an ->* expression is an lvalue if its second operand
4187 // is a pointer to data member and a prvalue otherwise.
4188 if (Result->isFunctionType()) {
4190 return Context.BoundMemberTy;
4191 } else if (isIndirect) {
4194 VK = LHS.get()->getValueKind();
4200 /// \brief Try to convert a type to another according to C++0x 5.16p3.
4202 /// This is part of the parameter validation for the ? operator. If either
4203 /// value operand is a class type, the two operands are attempted to be
4204 /// converted to each other. This function does the conversion in one direction.
4205 /// It returns true if the program is ill-formed and has already been diagnosed
4207 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
4208 SourceLocation QuestionLoc,
4209 bool &HaveConversion,
4211 HaveConversion = false;
4212 ToType = To->getType();
4214 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
4217 // The process for determining whether an operand expression E1 of type T1
4218 // can be converted to match an operand expression E2 of type T2 is defined
4220 // -- If E2 is an lvalue:
4221 bool ToIsLvalue = To->isLValue();
4223 // E1 can be converted to match E2 if E1 can be implicitly converted to
4224 // type "lvalue reference to T2", subject to the constraint that in the
4225 // conversion the reference must bind directly to E1.
4226 QualType T = Self.Context.getLValueReferenceType(ToType);
4227 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4229 InitializationSequence InitSeq(Self, Entity, Kind, From);
4230 if (InitSeq.isDirectReferenceBinding()) {
4232 HaveConversion = true;
4236 if (InitSeq.isAmbiguous())
4237 return InitSeq.Diagnose(Self, Entity, Kind, From);
4240 // -- If E2 is an rvalue, or if the conversion above cannot be done:
4241 // -- if E1 and E2 have class type, and the underlying class types are
4242 // the same or one is a base class of the other:
4243 QualType FTy = From->getType();
4244 QualType TTy = To->getType();
4245 const RecordType *FRec = FTy->getAs<RecordType>();
4246 const RecordType *TRec = TTy->getAs<RecordType>();
4247 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
4248 Self.IsDerivedFrom(FTy, TTy);
4250 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
4251 // E1 can be converted to match E2 if the class of T2 is the
4252 // same type as, or a base class of, the class of T1, and
4254 if (FRec == TRec || FDerivedFromT) {
4255 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
4256 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4257 InitializationSequence InitSeq(Self, Entity, Kind, From);
4259 HaveConversion = true;
4263 if (InitSeq.isAmbiguous())
4264 return InitSeq.Diagnose(Self, Entity, Kind, From);
4271 // -- Otherwise: E1 can be converted to match E2 if E1 can be
4272 // implicitly converted to the type that expression E2 would have
4273 // if E2 were converted to an rvalue (or the type it has, if E2 is
4276 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
4277 // to the array-to-pointer or function-to-pointer conversions.
4278 if (!TTy->getAs<TagType>())
4279 TTy = TTy.getUnqualifiedType();
4281 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4282 InitializationSequence InitSeq(Self, Entity, Kind, From);
4283 HaveConversion = !InitSeq.Failed();
4285 if (InitSeq.isAmbiguous())
4286 return InitSeq.Diagnose(Self, Entity, Kind, From);
4291 /// \brief Try to find a common type for two according to C++0x 5.16p5.
4293 /// This is part of the parameter validation for the ? operator. If either
4294 /// value operand is a class type, overload resolution is used to find a
4295 /// conversion to a common type.
4296 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
4297 SourceLocation QuestionLoc) {
4298 Expr *Args[2] = { LHS.get(), RHS.get() };
4299 OverloadCandidateSet CandidateSet(QuestionLoc);
4300 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
4303 OverloadCandidateSet::iterator Best;
4304 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
4306 // We found a match. Perform the conversions on the arguments and move on.
4308 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4309 Best->Conversions[0], Sema::AA_Converting);
4310 if (LHSRes.isInvalid())
4315 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4316 Best->Conversions[1], Sema::AA_Converting);
4317 if (RHSRes.isInvalid())
4321 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
4325 case OR_No_Viable_Function:
4327 // Emit a better diagnostic if one of the expressions is a null pointer
4328 // constant and the other is a pointer type. In this case, the user most
4329 // likely forgot to take the address of the other expression.
4330 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4333 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4334 << LHS.get()->getType() << RHS.get()->getType()
4335 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4339 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
4340 << LHS.get()->getType() << RHS.get()->getType()
4341 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4342 // FIXME: Print the possible common types by printing the return types of
4343 // the viable candidates.
4347 llvm_unreachable("Conditional operator has only built-in overloads");
4352 /// \brief Perform an "extended" implicit conversion as returned by
4353 /// TryClassUnification.
4354 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
4355 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4356 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
4358 Expr *Arg = E.take();
4359 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
4360 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
4361 if (Result.isInvalid())
4368 /// \brief Check the operands of ?: under C++ semantics.
4370 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4371 /// extension. In this case, LHS == Cond. (But they're not aliases.)
4372 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4373 ExprResult &RHS, ExprValueKind &VK,
4375 SourceLocation QuestionLoc) {
4376 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4377 // interface pointers.
4379 // C++11 [expr.cond]p1
4380 // The first expression is contextually converted to bool.
4381 if (!Cond.get()->isTypeDependent()) {
4382 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4383 if (CondRes.isInvalid())
4392 // Either of the arguments dependent?
4393 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
4394 return Context.DependentTy;
4396 // C++11 [expr.cond]p2
4397 // If either the second or the third operand has type (cv) void, ...
4398 QualType LTy = LHS.get()->getType();
4399 QualType RTy = RHS.get()->getType();
4400 bool LVoid = LTy->isVoidType();
4401 bool RVoid = RTy->isVoidType();
4402 if (LVoid || RVoid) {
4403 // ... then the [l2r] conversions are performed on the second and third
4405 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4406 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4407 if (LHS.isInvalid() || RHS.isInvalid())
4410 // Finish off the lvalue-to-rvalue conversion by copy-initializing a
4411 // temporary if necessary. DefaultFunctionArrayLvalueConversion doesn't
4412 // do this part for us.
4413 ExprResult &NonVoid = LVoid ? RHS : LHS;
4414 if (NonVoid.get()->getType()->isRecordType() &&
4415 NonVoid.get()->isGLValue()) {
4416 if (RequireNonAbstractType(QuestionLoc, NonVoid.get()->getType(),
4417 diag::err_allocation_of_abstract_type))
4419 InitializedEntity Entity =
4420 InitializedEntity::InitializeTemporary(NonVoid.get()->getType());
4421 NonVoid = PerformCopyInitialization(Entity, SourceLocation(), NonVoid);
4422 if (NonVoid.isInvalid())
4426 LTy = LHS.get()->getType();
4427 RTy = RHS.get()->getType();
4429 // ... and one of the following shall hold:
4430 // -- The second or the third operand (but not both) is a throw-
4431 // expression; the result is of the type of the other and is a prvalue.
4432 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenCasts());
4433 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenCasts());
4434 if (LThrow && !RThrow)
4436 if (RThrow && !LThrow)
4439 // -- Both the second and third operands have type void; the result is of
4440 // type void and is a prvalue.
4442 return Context.VoidTy;
4444 // Neither holds, error.
4445 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4446 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
4447 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4453 // C++11 [expr.cond]p3
4454 // Otherwise, if the second and third operand have different types, and
4455 // either has (cv) class type [...] an attempt is made to convert each of
4456 // those operands to the type of the other.
4457 if (!Context.hasSameType(LTy, RTy) &&
4458 (LTy->isRecordType() || RTy->isRecordType())) {
4459 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4460 // These return true if a single direction is already ambiguous.
4461 QualType L2RType, R2LType;
4462 bool HaveL2R, HaveR2L;
4463 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
4465 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
4468 // If both can be converted, [...] the program is ill-formed.
4469 if (HaveL2R && HaveR2L) {
4470 Diag(QuestionLoc, diag::err_conditional_ambiguous)
4471 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4475 // If exactly one conversion is possible, that conversion is applied to
4476 // the chosen operand and the converted operands are used in place of the
4477 // original operands for the remainder of this section.
4479 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
4481 LTy = LHS.get()->getType();
4482 } else if (HaveR2L) {
4483 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
4485 RTy = RHS.get()->getType();
4489 // C++11 [expr.cond]p3
4490 // if both are glvalues of the same value category and the same type except
4491 // for cv-qualification, an attempt is made to convert each of those
4492 // operands to the type of the other.
4493 ExprValueKind LVK = LHS.get()->getValueKind();
4494 ExprValueKind RVK = RHS.get()->getValueKind();
4495 if (!Context.hasSameType(LTy, RTy) &&
4496 Context.hasSameUnqualifiedType(LTy, RTy) &&
4497 LVK == RVK && LVK != VK_RValue) {
4498 // Since the unqualified types are reference-related and we require the
4499 // result to be as if a reference bound directly, the only conversion
4500 // we can perform is to add cv-qualifiers.
4501 Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
4502 Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
4503 if (RCVR.isStrictSupersetOf(LCVR)) {
4504 LHS = ImpCastExprToType(LHS.take(), RTy, CK_NoOp, LVK);
4505 LTy = LHS.get()->getType();
4507 else if (LCVR.isStrictSupersetOf(RCVR)) {
4508 RHS = ImpCastExprToType(RHS.take(), LTy, CK_NoOp, RVK);
4509 RTy = RHS.get()->getType();
4513 // C++11 [expr.cond]p4
4514 // If the second and third operands are glvalues of the same value
4515 // category and have the same type, the result is of that type and
4516 // value category and it is a bit-field if the second or the third
4517 // operand is a bit-field, or if both are bit-fields.
4518 // We only extend this to bitfields, not to the crazy other kinds of
4520 bool Same = Context.hasSameType(LTy, RTy);
4521 if (Same && LVK == RVK && LVK != VK_RValue &&
4522 LHS.get()->isOrdinaryOrBitFieldObject() &&
4523 RHS.get()->isOrdinaryOrBitFieldObject()) {
4524 VK = LHS.get()->getValueKind();
4525 if (LHS.get()->getObjectKind() == OK_BitField ||
4526 RHS.get()->getObjectKind() == OK_BitField)
4531 // C++11 [expr.cond]p5
4532 // Otherwise, the result is a prvalue. If the second and third operands
4533 // do not have the same type, and either has (cv) class type, ...
4534 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4535 // ... overload resolution is used to determine the conversions (if any)
4536 // to be applied to the operands. If the overload resolution fails, the
4537 // program is ill-formed.
4538 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4542 // C++11 [expr.cond]p6
4543 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
4544 // conversions are performed on the second and third operands.
4545 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4546 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4547 if (LHS.isInvalid() || RHS.isInvalid())
4549 LTy = LHS.get()->getType();
4550 RTy = RHS.get()->getType();
4552 // After those conversions, one of the following shall hold:
4553 // -- The second and third operands have the same type; the result
4554 // is of that type. If the operands have class type, the result
4555 // is a prvalue temporary of the result type, which is
4556 // copy-initialized from either the second operand or the third
4557 // operand depending on the value of the first operand.
4558 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4559 if (LTy->isRecordType()) {
4560 // The operands have class type. Make a temporary copy.
4561 if (RequireNonAbstractType(QuestionLoc, LTy,
4562 diag::err_allocation_of_abstract_type))
4564 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
4566 ExprResult LHSCopy = PerformCopyInitialization(Entity,
4569 if (LHSCopy.isInvalid())
4572 ExprResult RHSCopy = PerformCopyInitialization(Entity,
4575 if (RHSCopy.isInvalid())
4585 // Extension: conditional operator involving vector types.
4586 if (LTy->isVectorType() || RTy->isVectorType())
4587 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4589 // -- The second and third operands have arithmetic or enumeration type;
4590 // the usual arithmetic conversions are performed to bring them to a
4591 // common type, and the result is of that type.
4592 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4593 UsualArithmeticConversions(LHS, RHS);
4594 if (LHS.isInvalid() || RHS.isInvalid())
4596 return LHS.get()->getType();
4599 // -- The second and third operands have pointer type, or one has pointer
4600 // type and the other is a null pointer constant, or both are null
4601 // pointer constants, at least one of which is non-integral; pointer
4602 // conversions and qualification conversions are performed to bring them
4603 // to their composite pointer type. The result is of the composite
4605 // -- The second and third operands have pointer to member type, or one has
4606 // pointer to member type and the other is a null pointer constant;
4607 // pointer to member conversions and qualification conversions are
4608 // performed to bring them to a common type, whose cv-qualification
4609 // shall match the cv-qualification of either the second or the third
4610 // operand. The result is of the common type.
4611 bool NonStandardCompositeType = false;
4612 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
4613 isSFINAEContext()? 0 : &NonStandardCompositeType);
4614 if (!Composite.isNull()) {
4615 if (NonStandardCompositeType)
4617 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4618 << LTy << RTy << Composite
4619 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4624 // Similarly, attempt to find composite type of two objective-c pointers.
4625 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4626 if (!Composite.isNull())
4629 // Check if we are using a null with a non-pointer type.
4630 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4633 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4634 << LHS.get()->getType() << RHS.get()->getType()
4635 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4639 /// \brief Find a merged pointer type and convert the two expressions to it.
4641 /// This finds the composite pointer type (or member pointer type) for @p E1
4642 /// and @p E2 according to C++11 5.9p2. It converts both expressions to this
4643 /// type and returns it.
4644 /// It does not emit diagnostics.
4646 /// \param Loc The location of the operator requiring these two expressions to
4647 /// be converted to the composite pointer type.
4649 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4650 /// a non-standard (but still sane) composite type to which both expressions
4651 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4652 /// will be set true.
4653 QualType Sema::FindCompositePointerType(SourceLocation Loc,
4654 Expr *&E1, Expr *&E2,
4655 bool *NonStandardCompositeType) {
4656 if (NonStandardCompositeType)
4657 *NonStandardCompositeType = false;
4659 assert(getLangOpts().CPlusPlus && "This function assumes C++");
4660 QualType T1 = E1->getType(), T2 = E2->getType();
4663 // Pointer conversions and qualification conversions are performed on
4664 // pointer operands to bring them to their composite pointer type. If
4665 // one operand is a null pointer constant, the composite pointer type is
4666 // std::nullptr_t if the other operand is also a null pointer constant or,
4667 // if the other operand is a pointer, the type of the other operand.
4668 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4669 !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
4670 if (T1->isNullPtrType() &&
4671 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4672 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
4675 if (T2->isNullPtrType() &&
4676 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4677 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
4683 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4684 if (T2->isMemberPointerType())
4685 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
4687 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
4690 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4691 if (T1->isMemberPointerType())
4692 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
4694 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
4698 // Now both have to be pointers or member pointers.
4699 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4700 (!T2->isPointerType() && !T2->isMemberPointerType()))
4703 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4704 // the other has type "pointer to cv2 T" and the composite pointer type is
4705 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4706 // Otherwise, the composite pointer type is a pointer type similar to the
4707 // type of one of the operands, with a cv-qualification signature that is
4708 // the union of the cv-qualification signatures of the operand types.
4709 // In practice, the first part here is redundant; it's subsumed by the second.
4710 // What we do here is, we build the two possible composite types, and try the
4711 // conversions in both directions. If only one works, or if the two composite
4712 // types are the same, we have succeeded.
4713 // FIXME: extended qualifiers?
4714 typedef SmallVector<unsigned, 4> QualifierVector;
4715 QualifierVector QualifierUnion;
4716 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
4717 ContainingClassVector;
4718 ContainingClassVector MemberOfClass;
4719 QualType Composite1 = Context.getCanonicalType(T1),
4720 Composite2 = Context.getCanonicalType(T2);
4721 unsigned NeedConstBefore = 0;
4723 const PointerType *Ptr1, *Ptr2;
4724 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4725 (Ptr2 = Composite2->getAs<PointerType>())) {
4726 Composite1 = Ptr1->getPointeeType();
4727 Composite2 = Ptr2->getPointeeType();
4729 // If we're allowed to create a non-standard composite type, keep track
4730 // of where we need to fill in additional 'const' qualifiers.
4731 if (NonStandardCompositeType &&
4732 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4733 NeedConstBefore = QualifierUnion.size();
4735 QualifierUnion.push_back(
4736 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4737 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4741 const MemberPointerType *MemPtr1, *MemPtr2;
4742 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4743 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4744 Composite1 = MemPtr1->getPointeeType();
4745 Composite2 = MemPtr2->getPointeeType();
4747 // If we're allowed to create a non-standard composite type, keep track
4748 // of where we need to fill in additional 'const' qualifiers.
4749 if (NonStandardCompositeType &&
4750 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4751 NeedConstBefore = QualifierUnion.size();
4753 QualifierUnion.push_back(
4754 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4755 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4756 MemPtr2->getClass()));
4760 // FIXME: block pointer types?
4762 // Cannot unwrap any more types.
4766 if (NeedConstBefore && NonStandardCompositeType) {
4767 // Extension: Add 'const' to qualifiers that come before the first qualifier
4768 // mismatch, so that our (non-standard!) composite type meets the
4769 // requirements of C++ [conv.qual]p4 bullet 3.
4770 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4771 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4772 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4773 *NonStandardCompositeType = true;
4778 // Rewrap the composites as pointers or member pointers with the union CVRs.
4779 ContainingClassVector::reverse_iterator MOC
4780 = MemberOfClass.rbegin();
4781 for (QualifierVector::reverse_iterator
4782 I = QualifierUnion.rbegin(),
4783 E = QualifierUnion.rend();
4784 I != E; (void)++I, ++MOC) {
4785 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
4786 if (MOC->first && MOC->second) {
4787 // Rebuild member pointer type
4788 Composite1 = Context.getMemberPointerType(
4789 Context.getQualifiedType(Composite1, Quals),
4791 Composite2 = Context.getMemberPointerType(
4792 Context.getQualifiedType(Composite2, Quals),
4795 // Rebuild pointer type
4797 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4799 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
4803 // Try to convert to the first composite pointer type.
4804 InitializedEntity Entity1
4805 = InitializedEntity::InitializeTemporary(Composite1);
4806 InitializationKind Kind
4807 = InitializationKind::CreateCopy(Loc, SourceLocation());
4808 InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
4809 InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
4811 if (E1ToC1 && E2ToC1) {
4812 // Conversion to Composite1 is viable.
4813 if (!Context.hasSameType(Composite1, Composite2)) {
4814 // Composite2 is a different type from Composite1. Check whether
4815 // Composite2 is also viable.
4816 InitializedEntity Entity2
4817 = InitializedEntity::InitializeTemporary(Composite2);
4818 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4819 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
4820 if (E1ToC2 && E2ToC2) {
4821 // Both Composite1 and Composite2 are viable and are different;
4822 // this is an ambiguity.
4827 // Convert E1 to Composite1
4829 = E1ToC1.Perform(*this, Entity1, Kind, E1);
4830 if (E1Result.isInvalid())
4832 E1 = E1Result.takeAs<Expr>();
4834 // Convert E2 to Composite1
4836 = E2ToC1.Perform(*this, Entity1, Kind, E2);
4837 if (E2Result.isInvalid())
4839 E2 = E2Result.takeAs<Expr>();
4844 // Check whether Composite2 is viable.
4845 InitializedEntity Entity2
4846 = InitializedEntity::InitializeTemporary(Composite2);
4847 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4848 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
4849 if (!E1ToC2 || !E2ToC2)
4852 // Convert E1 to Composite2
4854 = E1ToC2.Perform(*this, Entity2, Kind, E1);
4855 if (E1Result.isInvalid())
4857 E1 = E1Result.takeAs<Expr>();
4859 // Convert E2 to Composite2
4861 = E2ToC2.Perform(*this, Entity2, Kind, E2);
4862 if (E2Result.isInvalid())
4864 E2 = E2Result.takeAs<Expr>();
4869 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
4873 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4875 // If the result is a glvalue, we shouldn't bind it.
4879 // In ARC, calls that return a retainable type can return retained,
4880 // in which case we have to insert a consuming cast.
4881 if (getLangOpts().ObjCAutoRefCount &&
4882 E->getType()->isObjCRetainableType()) {
4884 bool ReturnsRetained;
4886 // For actual calls, we compute this by examining the type of the
4888 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4889 Expr *Callee = Call->getCallee()->IgnoreParens();
4890 QualType T = Callee->getType();
4892 if (T == Context.BoundMemberTy) {
4893 // Handle pointer-to-members.
4894 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4895 T = BinOp->getRHS()->getType();
4896 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4897 T = Mem->getMemberDecl()->getType();
4900 if (const PointerType *Ptr = T->getAs<PointerType>())
4901 T = Ptr->getPointeeType();
4902 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4903 T = Ptr->getPointeeType();
4904 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4905 T = MemPtr->getPointeeType();
4907 const FunctionType *FTy = T->getAs<FunctionType>();
4908 assert(FTy && "call to value not of function type?");
4909 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4911 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4912 // type always produce a +1 object.
4913 } else if (isa<StmtExpr>(E)) {
4914 ReturnsRetained = true;
4916 // We hit this case with the lambda conversion-to-block optimization;
4917 // we don't want any extra casts here.
4918 } else if (isa<CastExpr>(E) &&
4919 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4922 // For message sends and property references, we try to find an
4923 // actual method. FIXME: we should infer retention by selector in
4924 // cases where we don't have an actual method.
4926 ObjCMethodDecl *D = 0;
4927 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4928 D = Send->getMethodDecl();
4929 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4930 D = BoxedExpr->getBoxingMethod();
4931 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4932 D = ArrayLit->getArrayWithObjectsMethod();
4933 } else if (ObjCDictionaryLiteral *DictLit
4934 = dyn_cast<ObjCDictionaryLiteral>(E)) {
4935 D = DictLit->getDictWithObjectsMethod();
4938 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
4940 // Don't do reclaims on performSelector calls; despite their
4941 // return type, the invoked method doesn't necessarily actually
4942 // return an object.
4943 if (!ReturnsRetained &&
4944 D && D->getMethodFamily() == OMF_performSelector)
4948 // Don't reclaim an object of Class type.
4949 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4952 ExprNeedsCleanups = true;
4954 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4955 : CK_ARCReclaimReturnedObject);
4956 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4960 if (!getLangOpts().CPlusPlus)
4963 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4964 // a fast path for the common case that the type is directly a RecordType.
4965 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4966 const RecordType *RT = 0;
4968 switch (T->getTypeClass()) {
4970 RT = cast<RecordType>(T);
4972 case Type::ConstantArray:
4973 case Type::IncompleteArray:
4974 case Type::VariableArray:
4975 case Type::DependentSizedArray:
4976 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4983 // That should be enough to guarantee that this type is complete, if we're
4984 // not processing a decltype expression.
4985 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4986 if (RD->isInvalidDecl() || RD->isDependentContext())
4989 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4990 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
4993 MarkFunctionReferenced(E->getExprLoc(), Destructor);
4994 CheckDestructorAccess(E->getExprLoc(), Destructor,
4995 PDiag(diag::err_access_dtor_temp)
4997 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
5000 // If destructor is trivial, we can avoid the extra copy.
5001 if (Destructor->isTrivial())
5004 // We need a cleanup, but we don't need to remember the temporary.
5005 ExprNeedsCleanups = true;
5008 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
5009 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
5012 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
5018 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
5019 if (SubExpr.isInvalid())
5022 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
5025 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
5026 assert(SubExpr && "sub expression can't be null!");
5028 CleanupVarDeclMarking();
5030 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
5031 assert(ExprCleanupObjects.size() >= FirstCleanup);
5032 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
5033 if (!ExprNeedsCleanups)
5036 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
5037 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
5038 ExprCleanupObjects.size() - FirstCleanup);
5040 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
5041 DiscardCleanupsInEvaluationContext();
5046 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
5047 assert(SubStmt && "sub statement can't be null!");
5049 CleanupVarDeclMarking();
5051 if (!ExprNeedsCleanups)
5054 // FIXME: In order to attach the temporaries, wrap the statement into
5055 // a StmtExpr; currently this is only used for asm statements.
5056 // This is hacky, either create a new CXXStmtWithTemporaries statement or
5057 // a new AsmStmtWithTemporaries.
5058 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
5061 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5063 return MaybeCreateExprWithCleanups(E);
5066 /// Process the expression contained within a decltype. For such expressions,
5067 /// certain semantic checks on temporaries are delayed until this point, and
5068 /// are omitted for the 'topmost' call in the decltype expression. If the
5069 /// topmost call bound a temporary, strip that temporary off the expression.
5070 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
5071 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
5073 // C++11 [expr.call]p11:
5074 // If a function call is a prvalue of object type,
5075 // -- if the function call is either
5076 // -- the operand of a decltype-specifier, or
5077 // -- the right operand of a comma operator that is the operand of a
5078 // decltype-specifier,
5079 // a temporary object is not introduced for the prvalue.
5081 // Recursively rebuild ParenExprs and comma expressions to strip out the
5082 // outermost CXXBindTemporaryExpr, if any.
5083 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5084 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5085 if (SubExpr.isInvalid())
5087 if (SubExpr.get() == PE->getSubExpr())
5089 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
5091 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5092 if (BO->getOpcode() == BO_Comma) {
5093 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5094 if (RHS.isInvalid())
5096 if (RHS.get() == BO->getRHS())
5098 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
5099 BO_Comma, BO->getType(),
5101 BO->getObjectKind(),
5102 BO->getOperatorLoc(),
5103 BO->isFPContractable()));
5107 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
5109 E = TopBind->getSubExpr();
5111 // Disable the special decltype handling now.
5112 ExprEvalContexts.back().IsDecltype = false;
5114 // In MS mode, don't perform any extra checking of call return types within a
5115 // decltype expression.
5116 if (getLangOpts().MicrosoftMode)
5119 // Perform the semantic checks we delayed until this point.
5120 CallExpr *TopCall = dyn_cast<CallExpr>(E);
5121 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
5123 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
5124 if (Call == TopCall)
5127 if (CheckCallReturnType(Call->getCallReturnType(),
5128 Call->getLocStart(),
5129 Call, Call->getDirectCallee()))
5133 // Now all relevant types are complete, check the destructors are accessible
5134 // and non-deleted, and annotate them on the temporaries.
5135 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
5137 CXXBindTemporaryExpr *Bind =
5138 ExprEvalContexts.back().DelayedDecltypeBinds[I];
5139 if (Bind == TopBind)
5142 CXXTemporary *Temp = Bind->getTemporary();
5145 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5146 CXXDestructorDecl *Destructor = LookupDestructor(RD);
5147 Temp->setDestructor(Destructor);
5149 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
5150 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
5151 PDiag(diag::err_access_dtor_temp)
5152 << Bind->getType());
5153 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
5156 // We need a cleanup, but we don't need to remember the temporary.
5157 ExprNeedsCleanups = true;
5160 // Possibly strip off the top CXXBindTemporaryExpr.
5164 /// Note a set of 'operator->' functions that were used for a member access.
5165 static void noteOperatorArrows(Sema &S,
5166 llvm::ArrayRef<FunctionDecl *> OperatorArrows) {
5167 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
5168 // FIXME: Make this configurable?
5170 if (OperatorArrows.size() > Limit) {
5171 // Produce Limit-1 normal notes and one 'skipping' note.
5172 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
5173 SkipCount = OperatorArrows.size() - (Limit - 1);
5176 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
5177 if (I == SkipStart) {
5178 S.Diag(OperatorArrows[I]->getLocation(),
5179 diag::note_operator_arrows_suppressed)
5183 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
5184 << OperatorArrows[I]->getCallResultType();
5191 Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
5192 tok::TokenKind OpKind, ParsedType &ObjectType,
5193 bool &MayBePseudoDestructor) {
5194 // Since this might be a postfix expression, get rid of ParenListExprs.
5195 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
5196 if (Result.isInvalid()) return ExprError();
5197 Base = Result.get();
5199 Result = CheckPlaceholderExpr(Base);
5200 if (Result.isInvalid()) return ExprError();
5201 Base = Result.take();
5203 QualType BaseType = Base->getType();
5204 MayBePseudoDestructor = false;
5205 if (BaseType->isDependentType()) {
5206 // If we have a pointer to a dependent type and are using the -> operator,
5207 // the object type is the type that the pointer points to. We might still
5208 // have enough information about that type to do something useful.
5209 if (OpKind == tok::arrow)
5210 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
5211 BaseType = Ptr->getPointeeType();
5213 ObjectType = ParsedType::make(BaseType);
5214 MayBePseudoDestructor = true;
5218 // C++ [over.match.oper]p8:
5219 // [...] When operator->returns, the operator-> is applied to the value
5220 // returned, with the original second operand.
5221 if (OpKind == tok::arrow) {
5222 QualType StartingType = BaseType;
5223 bool NoArrowOperatorFound = false;
5224 bool FirstIteration = true;
5225 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
5226 // The set of types we've considered so far.
5227 llvm::SmallPtrSet<CanQualType,8> CTypes;
5228 SmallVector<FunctionDecl*, 8> OperatorArrows;
5229 CTypes.insert(Context.getCanonicalType(BaseType));
5231 while (BaseType->isRecordType()) {
5232 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
5233 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
5234 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
5235 noteOperatorArrows(*this, OperatorArrows);
5236 Diag(OpLoc, diag::note_operator_arrow_depth)
5237 << getLangOpts().ArrowDepth;
5241 Result = BuildOverloadedArrowExpr(
5243 // When in a template specialization and on the first loop iteration,
5244 // potentially give the default diagnostic (with the fixit in a
5245 // separate note) instead of having the error reported back to here
5246 // and giving a diagnostic with a fixit attached to the error itself.
5247 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
5249 : &NoArrowOperatorFound);
5250 if (Result.isInvalid()) {
5251 if (NoArrowOperatorFound) {
5252 if (FirstIteration) {
5253 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5254 << BaseType << 1 << Base->getSourceRange()
5255 << FixItHint::CreateReplacement(OpLoc, ".");
5256 OpKind = tok::period;
5259 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5260 << BaseType << Base->getSourceRange();
5261 CallExpr *CE = dyn_cast<CallExpr>(Base);
5262 if (Decl *CD = (CE ? CE->getCalleeDecl() : 0)) {
5263 Diag(CD->getLocStart(),
5264 diag::note_member_reference_arrow_from_operator_arrow);
5269 Base = Result.get();
5270 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
5271 OperatorArrows.push_back(OpCall->getDirectCallee());
5272 BaseType = Base->getType();
5273 CanQualType CBaseType = Context.getCanonicalType(BaseType);
5274 if (!CTypes.insert(CBaseType)) {
5275 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
5276 noteOperatorArrows(*this, OperatorArrows);
5279 FirstIteration = false;
5282 if (OpKind == tok::arrow &&
5283 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
5284 BaseType = BaseType->getPointeeType();
5287 // Objective-C properties allow "." access on Objective-C pointer types,
5288 // so adjust the base type to the object type itself.
5289 if (BaseType->isObjCObjectPointerType())
5290 BaseType = BaseType->getPointeeType();
5292 // C++ [basic.lookup.classref]p2:
5293 // [...] If the type of the object expression is of pointer to scalar
5294 // type, the unqualified-id is looked up in the context of the complete
5295 // postfix-expression.
5297 // This also indicates that we could be parsing a pseudo-destructor-name.
5298 // Note that Objective-C class and object types can be pseudo-destructor
5299 // expressions or normal member (ivar or property) access expressions.
5300 if (BaseType->isObjCObjectOrInterfaceType()) {
5301 MayBePseudoDestructor = true;
5302 } else if (!BaseType->isRecordType()) {
5303 ObjectType = ParsedType();
5304 MayBePseudoDestructor = true;
5308 // The object type must be complete (or dependent), or
5309 // C++11 [expr.prim.general]p3:
5310 // Unlike the object expression in other contexts, *this is not required to
5311 // be of complete type for purposes of class member access (5.2.5) outside
5312 // the member function body.
5313 if (!BaseType->isDependentType() &&
5314 !isThisOutsideMemberFunctionBody(BaseType) &&
5315 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
5318 // C++ [basic.lookup.classref]p2:
5319 // If the id-expression in a class member access (5.2.5) is an
5320 // unqualified-id, and the type of the object expression is of a class
5321 // type C (or of pointer to a class type C), the unqualified-id is looked
5322 // up in the scope of class C. [...]
5323 ObjectType = ParsedType::make(BaseType);
5327 ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
5329 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
5330 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
5331 << isa<CXXPseudoDestructorExpr>(MemExpr)
5332 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
5334 return ActOnCallExpr(/*Scope*/ 0,
5336 /*LPLoc*/ ExpectedLParenLoc,
5338 /*RPLoc*/ ExpectedLParenLoc);
5341 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
5342 tok::TokenKind& OpKind, SourceLocation OpLoc) {
5343 if (Base->hasPlaceholderType()) {
5344 ExprResult result = S.CheckPlaceholderExpr(Base);
5345 if (result.isInvalid()) return true;
5346 Base = result.take();
5348 ObjectType = Base->getType();
5350 // C++ [expr.pseudo]p2:
5351 // The left-hand side of the dot operator shall be of scalar type. The
5352 // left-hand side of the arrow operator shall be of pointer to scalar type.
5353 // This scalar type is the object type.
5354 // Note that this is rather different from the normal handling for the
5356 if (OpKind == tok::arrow) {
5357 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
5358 ObjectType = Ptr->getPointeeType();
5359 } else if (!Base->isTypeDependent()) {
5360 // The user wrote "p->" when she probably meant "p."; fix it.
5361 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5362 << ObjectType << true
5363 << FixItHint::CreateReplacement(OpLoc, ".");
5364 if (S.isSFINAEContext())
5367 OpKind = tok::period;
5374 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
5375 SourceLocation OpLoc,
5376 tok::TokenKind OpKind,
5377 const CXXScopeSpec &SS,
5378 TypeSourceInfo *ScopeTypeInfo,
5379 SourceLocation CCLoc,
5380 SourceLocation TildeLoc,
5381 PseudoDestructorTypeStorage Destructed,
5382 bool HasTrailingLParen) {
5383 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
5385 QualType ObjectType;
5386 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5389 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
5390 !ObjectType->isVectorType()) {
5391 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
5392 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
5394 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
5395 << ObjectType << Base->getSourceRange();
5399 // C++ [expr.pseudo]p2:
5400 // [...] The cv-unqualified versions of the object type and of the type
5401 // designated by the pseudo-destructor-name shall be the same type.
5402 if (DestructedTypeInfo) {
5403 QualType DestructedType = DestructedTypeInfo->getType();
5404 SourceLocation DestructedTypeStart
5405 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
5406 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
5407 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
5408 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
5409 << ObjectType << DestructedType << Base->getSourceRange()
5410 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5412 // Recover by setting the destructed type to the object type.
5413 DestructedType = ObjectType;
5414 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5415 DestructedTypeStart);
5416 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5417 } else if (DestructedType.getObjCLifetime() !=
5418 ObjectType.getObjCLifetime()) {
5420 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
5421 // Okay: just pretend that the user provided the correctly-qualified
5424 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
5425 << ObjectType << DestructedType << Base->getSourceRange()
5426 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5429 // Recover by setting the destructed type to the object type.
5430 DestructedType = ObjectType;
5431 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5432 DestructedTypeStart);
5433 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5438 // C++ [expr.pseudo]p2:
5439 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5442 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
5444 // shall designate the same scalar type.
5445 if (ScopeTypeInfo) {
5446 QualType ScopeType = ScopeTypeInfo->getType();
5447 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
5448 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
5450 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
5451 diag::err_pseudo_dtor_type_mismatch)
5452 << ObjectType << ScopeType << Base->getSourceRange()
5453 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
5455 ScopeType = QualType();
5461 = new (Context) CXXPseudoDestructorExpr(Context, Base,
5462 OpKind == tok::arrow, OpLoc,
5463 SS.getWithLocInContext(Context),
5469 if (HasTrailingLParen)
5470 return Owned(Result);
5472 return DiagnoseDtorReference(Destructed.getLocation(), Result);
5475 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5476 SourceLocation OpLoc,
5477 tok::TokenKind OpKind,
5479 UnqualifiedId &FirstTypeName,
5480 SourceLocation CCLoc,
5481 SourceLocation TildeLoc,
5482 UnqualifiedId &SecondTypeName,
5483 bool HasTrailingLParen) {
5484 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5485 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5486 "Invalid first type name in pseudo-destructor");
5487 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5488 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5489 "Invalid second type name in pseudo-destructor");
5491 QualType ObjectType;
5492 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5495 // Compute the object type that we should use for name lookup purposes. Only
5496 // record types and dependent types matter.
5497 ParsedType ObjectTypePtrForLookup;
5499 if (ObjectType->isRecordType())
5500 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
5501 else if (ObjectType->isDependentType())
5502 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
5505 // Convert the name of the type being destructed (following the ~) into a
5506 // type (with source-location information).
5507 QualType DestructedType;
5508 TypeSourceInfo *DestructedTypeInfo = 0;
5509 PseudoDestructorTypeStorage Destructed;
5510 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5511 ParsedType T = getTypeName(*SecondTypeName.Identifier,
5512 SecondTypeName.StartLocation,
5513 S, &SS, true, false, ObjectTypePtrForLookup);
5515 ((SS.isSet() && !computeDeclContext(SS, false)) ||
5516 (!SS.isSet() && ObjectType->isDependentType()))) {
5517 // The name of the type being destroyed is a dependent name, and we
5518 // couldn't find anything useful in scope. Just store the identifier and
5519 // it's location, and we'll perform (qualified) name lookup again at
5520 // template instantiation time.
5521 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5522 SecondTypeName.StartLocation);
5524 Diag(SecondTypeName.StartLocation,
5525 diag::err_pseudo_dtor_destructor_non_type)
5526 << SecondTypeName.Identifier << ObjectType;
5527 if (isSFINAEContext())
5530 // Recover by assuming we had the right type all along.
5531 DestructedType = ObjectType;
5533 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
5535 // Resolve the template-id to a type.
5536 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
5537 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5538 TemplateId->NumArgs);
5539 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5540 TemplateId->TemplateKWLoc,
5541 TemplateId->Template,
5542 TemplateId->TemplateNameLoc,
5543 TemplateId->LAngleLoc,
5545 TemplateId->RAngleLoc);
5546 if (T.isInvalid() || !T.get()) {
5547 // Recover by assuming we had the right type all along.
5548 DestructedType = ObjectType;
5550 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
5553 // If we've performed some kind of recovery, (re-)build the type source
5555 if (!DestructedType.isNull()) {
5556 if (!DestructedTypeInfo)
5557 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
5558 SecondTypeName.StartLocation);
5559 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5562 // Convert the name of the scope type (the type prior to '::') into a type.
5563 TypeSourceInfo *ScopeTypeInfo = 0;
5565 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5566 FirstTypeName.Identifier) {
5567 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5568 ParsedType T = getTypeName(*FirstTypeName.Identifier,
5569 FirstTypeName.StartLocation,
5570 S, &SS, true, false, ObjectTypePtrForLookup);
5572 Diag(FirstTypeName.StartLocation,
5573 diag::err_pseudo_dtor_destructor_non_type)
5574 << FirstTypeName.Identifier << ObjectType;
5576 if (isSFINAEContext())
5579 // Just drop this type. It's unnecessary anyway.
5580 ScopeType = QualType();
5582 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
5584 // Resolve the template-id to a type.
5585 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
5586 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5587 TemplateId->NumArgs);
5588 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5589 TemplateId->TemplateKWLoc,
5590 TemplateId->Template,
5591 TemplateId->TemplateNameLoc,
5592 TemplateId->LAngleLoc,
5594 TemplateId->RAngleLoc);
5595 if (T.isInvalid() || !T.get()) {
5596 // Recover by dropping this type.
5597 ScopeType = QualType();
5599 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
5603 if (!ScopeType.isNull() && !ScopeTypeInfo)
5604 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5605 FirstTypeName.StartLocation);
5608 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
5609 ScopeTypeInfo, CCLoc, TildeLoc,
5610 Destructed, HasTrailingLParen);
5613 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5614 SourceLocation OpLoc,
5615 tok::TokenKind OpKind,
5616 SourceLocation TildeLoc,
5618 bool HasTrailingLParen) {
5619 QualType ObjectType;
5620 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5623 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5626 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5627 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5628 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5629 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5631 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5632 0, SourceLocation(), TildeLoc,
5633 Destructed, HasTrailingLParen);
5636 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
5637 CXXConversionDecl *Method,
5638 bool HadMultipleCandidates) {
5639 if (Method->getParent()->isLambda() &&
5640 Method->getConversionType()->isBlockPointerType()) {
5641 // This is a lambda coversion to block pointer; check if the argument
5644 CastExpr *CE = dyn_cast<CastExpr>(SubE);
5645 if (CE && CE->getCastKind() == CK_NoOp)
5646 SubE = CE->getSubExpr();
5647 SubE = SubE->IgnoreParens();
5648 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5649 SubE = BE->getSubExpr();
5650 if (isa<LambdaExpr>(SubE)) {
5651 // For the conversion to block pointer on a lambda expression, we
5652 // construct a special BlockLiteral instead; this doesn't really make
5653 // a difference in ARC, but outside of ARC the resulting block literal
5654 // follows the normal lifetime rules for block literals instead of being
5656 DiagnosticErrorTrap Trap(Diags);
5657 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5660 if (Exp.isInvalid())
5661 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5667 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5669 if (Exp.isInvalid())
5673 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
5674 SourceLocation(), Context.BoundMemberTy,
5675 VK_RValue, OK_Ordinary);
5676 if (HadMultipleCandidates)
5677 ME->setHadMultipleCandidates(true);
5678 MarkMemberReferenced(ME);
5680 QualType ResultType = Method->getResultType();
5681 ExprValueKind VK = Expr::getValueKindForType(ResultType);
5682 ResultType = ResultType.getNonLValueExprType(Context);
5684 CXXMemberCallExpr *CE =
5685 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
5686 Exp.get()->getLocEnd());
5690 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5691 SourceLocation RParen) {
5692 CanThrowResult CanThrow = canThrow(Operand);
5693 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
5694 CanThrow, KeyLoc, RParen));
5697 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5698 Expr *Operand, SourceLocation RParen) {
5699 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
5702 static bool IsSpecialDiscardedValue(Expr *E) {
5703 // In C++11, discarded-value expressions of a certain form are special,
5704 // according to [expr]p10:
5705 // The lvalue-to-rvalue conversion (4.1) is applied only if the
5706 // expression is an lvalue of volatile-qualified type and it has
5707 // one of the following forms:
5708 E = E->IgnoreParens();
5710 // - id-expression (5.1.1),
5711 if (isa<DeclRefExpr>(E))
5714 // - subscripting (5.2.1),
5715 if (isa<ArraySubscriptExpr>(E))
5718 // - class member access (5.2.5),
5719 if (isa<MemberExpr>(E))
5722 // - indirection (5.3.1),
5723 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
5724 if (UO->getOpcode() == UO_Deref)
5727 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5728 // - pointer-to-member operation (5.5),
5729 if (BO->isPtrMemOp())
5732 // - comma expression (5.18) where the right operand is one of the above.
5733 if (BO->getOpcode() == BO_Comma)
5734 return IsSpecialDiscardedValue(BO->getRHS());
5737 // - conditional expression (5.16) where both the second and the third
5738 // operands are one of the above, or
5739 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
5740 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
5741 IsSpecialDiscardedValue(CO->getFalseExpr());
5742 // The related edge case of "*x ?: *x".
5743 if (BinaryConditionalOperator *BCO =
5744 dyn_cast<BinaryConditionalOperator>(E)) {
5745 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
5746 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
5747 IsSpecialDiscardedValue(BCO->getFalseExpr());
5750 // Objective-C++ extensions to the rule.
5751 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
5757 /// Perform the conversions required for an expression used in a
5758 /// context that ignores the result.
5759 ExprResult Sema::IgnoredValueConversions(Expr *E) {
5760 if (E->hasPlaceholderType()) {
5761 ExprResult result = CheckPlaceholderExpr(E);
5762 if (result.isInvalid()) return Owned(E);
5767 // [Except in specific positions,] an lvalue that does not have
5768 // array type is converted to the value stored in the
5769 // designated object (and is no longer an lvalue).
5770 if (E->isRValue()) {
5771 // In C, function designators (i.e. expressions of function type)
5772 // are r-values, but we still want to do function-to-pointer decay
5773 // on them. This is both technically correct and convenient for
5775 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
5776 return DefaultFunctionArrayConversion(E);
5781 if (getLangOpts().CPlusPlus) {
5782 // The C++11 standard defines the notion of a discarded-value expression;
5783 // normally, we don't need to do anything to handle it, but if it is a
5784 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
5786 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
5787 E->getType().isVolatileQualified() &&
5788 IsSpecialDiscardedValue(E)) {
5789 ExprResult Res = DefaultLvalueConversion(E);
5790 if (Res.isInvalid())
5797 // GCC seems to also exclude expressions of incomplete enum type.
5798 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5799 if (!T->getDecl()->isComplete()) {
5800 // FIXME: stupid workaround for a codegen bug!
5801 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5806 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5807 if (Res.isInvalid())
5811 if (!E->getType()->isVoidType())
5812 RequireCompleteType(E->getExprLoc(), E->getType(),
5813 diag::err_incomplete_type);
5817 // If we can unambiguously determine whether Var can never be used
5818 // in a constant expression, return true.
5819 // - if the variable and its initializer are non-dependent, then
5820 // we can unambiguously check if the variable is a constant expression.
5821 // - if the initializer is not value dependent - we can determine whether
5822 // it can be used to initialize a constant expression. If Init can not
5823 // be used to initialize a constant expression we conclude that Var can
5824 // never be a constant expression.
5825 // - FXIME: if the initializer is dependent, we can still do some analysis and
5826 // identify certain cases unambiguously as non-const by using a Visitor:
5827 // - such as those that involve odr-use of a ParmVarDecl, involve a new
5828 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
5829 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
5830 ASTContext &Context) {
5831 if (isa<ParmVarDecl>(Var)) return true;
5832 const VarDecl *DefVD = 0;
5834 // If there is no initializer - this can not be a constant expression.
5835 if (!Var->getAnyInitializer(DefVD)) return true;
5837 if (DefVD->isWeak()) return false;
5838 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
5840 Expr *Init = cast<Expr>(Eval->Value);
5842 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
5843 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
5844 // of value-dependent expressions, and use it here to determine whether the
5845 // initializer is a potential constant expression.
5849 return !IsVariableAConstantExpression(Var, Context);
5852 /// \brief Check if the current lambda scope has any potential captures, and
5853 /// whether they can be captured by any of the enclosing lambdas that are
5854 /// ready to capture. If there is a lambda that can capture a nested
5855 /// potential-capture, go ahead and do so. Also, check to see if any
5856 /// variables are uncaptureable or do not involve an odr-use so do not
5857 /// need to be captured.
5859 static void CheckLambdaCaptures(Expr *const FE,
5860 LambdaScopeInfo *const CurrentLSI, Sema &S) {
5862 assert(!S.isUnevaluatedContext());
5863 assert(S.CurContext->isDependentContext());
5864 const bool IsFullExprInstantiationDependent =
5865 FE->isInstantiationDependent();
5866 // All the potentially captureable variables in the current nested
5867 // lambda (within a generic outer lambda), must be captured by an
5868 // outer lambda that is enclosed within a non-dependent context.
5870 for (size_t I = 0, N = CurrentLSI->getNumPotentialVariableCaptures();
5874 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
5876 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
5877 !IsFullExprInstantiationDependent)
5879 // Climb up until we find a lambda that can capture:
5880 // - a generic-or-non-generic lambda call operator that is enclosed
5881 // within a non-dependent context.
5882 unsigned FunctionScopeIndexOfCapturableLambda = 0;
5883 if (GetInnermostEnclosingCapturableLambda(
5884 S.FunctionScopes, FunctionScopeIndexOfCapturableLambda,
5885 S.CurContext, Var, S)) {
5886 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(),
5887 S, &FunctionScopeIndexOfCapturableLambda);
5889 const bool IsVarNeverAConstantExpression =
5890 VariableCanNeverBeAConstantExpression(Var, S.Context);
5891 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
5892 // This full expression is not instantiation dependent or the variable
5893 // can not be used in a constant expression - which means
5894 // this variable must be odr-used here, so diagnose a
5895 // capture violation early, if the variable is un-captureable.
5896 // This is purely for diagnosing errors early. Otherwise, this
5897 // error would get diagnosed when the lambda becomes capture ready.
5898 QualType CaptureType, DeclRefType;
5899 SourceLocation ExprLoc = VarExpr->getExprLoc();
5900 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5901 /*EllipsisLoc*/ SourceLocation(),
5902 /*BuildAndDiagnose*/false, CaptureType,
5904 // We will never be able to capture this variable, and we need
5905 // to be able to in any and all instantiations, so diagnose it.
5906 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5907 /*EllipsisLoc*/ SourceLocation(),
5908 /*BuildAndDiagnose*/true, CaptureType,
5914 if (CurrentLSI->hasPotentialThisCapture()) {
5915 unsigned FunctionScopeIndexOfCapturableLambda = 0;
5916 if (GetInnermostEnclosingCapturableLambda(
5917 S.FunctionScopes, FunctionScopeIndexOfCapturableLambda,
5918 S.CurContext, /*0 is 'this'*/ 0, S)) {
5919 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
5920 /*Explicit*/false, /*BuildAndDiagnose*/true,
5921 &FunctionScopeIndexOfCapturableLambda);
5924 CurrentLSI->clearPotentialCaptures();
5928 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
5929 bool DiscardedValue,
5931 bool IsLambdaInitCaptureInitializer) {
5932 ExprResult FullExpr = Owned(FE);
5934 if (!FullExpr.get())
5937 // If we are an init-expression in a lambdas init-capture, we should not
5938 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
5939 // containing full-expression is done).
5940 // template<class ... Ts> void test(Ts ... t) {
5941 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
5945 // FIXME: This is a hack. It would be better if we pushed the lambda scope
5946 // when we parse the lambda introducer, and teach capturing (but not
5947 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
5948 // corresponding class yet (that is, have LambdaScopeInfo either represent a
5949 // lambda where we've entered the introducer but not the body, or represent a
5950 // lambda where we've entered the body, depending on where the
5951 // parser/instantiation has got to).
5952 if (!IsLambdaInitCaptureInitializer &&
5953 DiagnoseUnexpandedParameterPack(FullExpr.get()))
5956 // Top-level expressions default to 'id' when we're in a debugger.
5957 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
5958 FullExpr.get()->getType() == Context.UnknownAnyTy) {
5959 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5960 if (FullExpr.isInvalid())
5964 if (DiscardedValue) {
5965 FullExpr = CheckPlaceholderExpr(FullExpr.take());
5966 if (FullExpr.isInvalid())
5969 FullExpr = IgnoredValueConversions(FullExpr.take());
5970 if (FullExpr.isInvalid())
5974 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
5976 // At the end of this full expression (which could be a deeply nested
5977 // lambda), if there is a potential capture within the nested lambda,
5978 // have the outer capture-able lambda try and capture it.
5979 // Consider the following code:
5980 // void f(int, int);
5981 // void f(const int&, double);
5983 // const int x = 10, y = 20;
5984 // auto L = [=](auto a) {
5985 // auto M = [=](auto b) {
5986 // f(x, b); <-- requires x to be captured by L and M
5987 // f(y, a); <-- requires y to be captured by L, but not all Ms
5992 // FIXME: Also consider what happens for something like this that involves
5993 // the gnu-extension statement-expressions or even lambda-init-captures:
5996 // auto L = [&](auto a) {
5997 // +n + ({ 0; a; });
6001 // Here, we see +n, and then the full-expression 0; ends, so we don't
6002 // capture n (and instead remove it from our list of potential captures),
6003 // and then the full-expression +n + ({ 0; }); ends, but it's too late
6004 // for us to see that we need to capture n after all.
6006 LambdaScopeInfo *const CurrentLSI = getCurLambda();
6007 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
6008 // even if CurContext is not a lambda call operator. Refer to that Bug Report
6009 // for an example of the code that might cause this asynchrony.
6010 // By ensuring we are in the context of a lambda's call operator
6011 // we can fix the bug (we only need to check whether we need to capture
6012 // if we are within a lambda's body); but per the comments in that
6013 // PR, a proper fix would entail :
6014 // "Alternative suggestion:
6015 // - Add to Sema an integer holding the smallest (outermost) scope
6016 // index that we are *lexically* within, and save/restore/set to
6017 // FunctionScopes.size() in InstantiatingTemplate's
6018 // constructor/destructor.
6019 // - Teach the handful of places that iterate over FunctionScopes to
6020 // stop at the outermost enclosing lexical scope."
6021 const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
6022 if (IsInLambdaDeclContext && CurrentLSI &&
6023 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
6024 CheckLambdaCaptures(FE, CurrentLSI, *this);
6025 return MaybeCreateExprWithCleanups(FullExpr);
6028 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
6029 if (!FullStmt) return StmtError();
6031 return MaybeCreateStmtWithCleanups(FullStmt);
6034 Sema::IfExistsResult
6035 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
6037 const DeclarationNameInfo &TargetNameInfo) {
6038 DeclarationName TargetName = TargetNameInfo.getName();
6040 return IER_DoesNotExist;
6042 // If the name itself is dependent, then the result is dependent.
6043 if (TargetName.isDependentName())
6044 return IER_Dependent;
6046 // Do the redeclaration lookup in the current scope.
6047 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
6048 Sema::NotForRedeclaration);
6049 LookupParsedName(R, S, &SS);
6050 R.suppressDiagnostics();
6052 switch (R.getResultKind()) {
6053 case LookupResult::Found:
6054 case LookupResult::FoundOverloaded:
6055 case LookupResult::FoundUnresolvedValue:
6056 case LookupResult::Ambiguous:
6059 case LookupResult::NotFound:
6060 return IER_DoesNotExist;
6062 case LookupResult::NotFoundInCurrentInstantiation:
6063 return IER_Dependent;
6066 llvm_unreachable("Invalid LookupResult Kind!");
6069 Sema::IfExistsResult
6070 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
6071 bool IsIfExists, CXXScopeSpec &SS,
6072 UnqualifiedId &Name) {
6073 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6075 // Check for unexpanded parameter packs.
6076 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
6077 collectUnexpandedParameterPacks(SS, Unexpanded);
6078 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
6079 if (!Unexpanded.empty()) {
6080 DiagnoseUnexpandedParameterPacks(KeywordLoc,
6081 IsIfExists? UPPC_IfExists
6087 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);