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 "clang/Sema/DeclSpec.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/Sema/ParsedTemplate.h"
20 #include "clang/Sema/ScopeInfo.h"
21 #include "clang/Sema/Scope.h"
22 #include "clang/Sema/TemplateDeduction.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/CharUnits.h"
25 #include "clang/AST/CXXInheritance.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "TypeLocBuilder.h"
34 #include "llvm/ADT/APInt.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/Support/ErrorHandling.h"
37 using namespace clang;
40 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
42 SourceLocation NameLoc,
43 Scope *S, CXXScopeSpec &SS,
44 ParsedType ObjectTypePtr,
45 bool EnteringContext) {
46 // Determine where to perform name lookup.
48 // FIXME: This area of the standard is very messy, and the current
49 // wording is rather unclear about which scopes we search for the
50 // destructor name; see core issues 399 and 555. Issue 399 in
51 // particular shows where the current description of destructor name
52 // lookup is completely out of line with existing practice, e.g.,
53 // this appears to be ill-formed:
56 // template <typename T> struct S {
61 // void f(N::S<int>* s) {
62 // s->N::S<int>::~S();
65 // See also PR6358 and PR6359.
66 // For this reason, we're currently only doing the C++03 version of this
67 // code; the C++0x version has to wait until we get a proper spec.
69 DeclContext *LookupCtx = 0;
70 bool isDependent = false;
71 bool LookInScope = false;
73 // If we have an object type, it's because we are in a
74 // pseudo-destructor-expression or a member access expression, and
75 // we know what type we're looking for.
77 SearchType = GetTypeFromParser(ObjectTypePtr);
80 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
82 bool AlreadySearched = false;
83 bool LookAtPrefix = true;
84 // C++ [basic.lookup.qual]p6:
85 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
86 // the type-names are looked up as types in the scope designated by the
87 // nested-name-specifier. In a qualified-id of the form:
89 // ::[opt] nested-name-specifier ~ class-name
91 // where the nested-name-specifier designates a namespace scope, and in
92 // a qualified-id of the form:
94 // ::opt nested-name-specifier class-name :: ~ class-name
96 // the class-names are looked up as types in the scope designated by
97 // the nested-name-specifier.
99 // Here, we check the first case (completely) and determine whether the
100 // code below is permitted to look at the prefix of the
101 // nested-name-specifier.
102 DeclContext *DC = computeDeclContext(SS, EnteringContext);
103 if (DC && DC->isFileContext()) {
104 AlreadySearched = true;
107 } else if (DC && isa<CXXRecordDecl>(DC))
108 LookAtPrefix = false;
110 // The second case from the C++03 rules quoted further above.
111 NestedNameSpecifier *Prefix = 0;
112 if (AlreadySearched) {
113 // Nothing left to do.
114 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
115 CXXScopeSpec PrefixSS;
116 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
117 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
118 isDependent = isDependentScopeSpecifier(PrefixSS);
119 } else if (ObjectTypePtr) {
120 LookupCtx = computeDeclContext(SearchType);
121 isDependent = SearchType->isDependentType();
123 LookupCtx = computeDeclContext(SS, EnteringContext);
124 isDependent = LookupCtx && LookupCtx->isDependentContext();
128 } else if (ObjectTypePtr) {
129 // C++ [basic.lookup.classref]p3:
130 // If the unqualified-id is ~type-name, the type-name is looked up
131 // in the context of the entire postfix-expression. If the type T
132 // of the object expression is of a class type C, the type-name is
133 // also looked up in the scope of class C. At least one of the
134 // lookups shall find a name that refers to (possibly
136 LookupCtx = computeDeclContext(SearchType);
137 isDependent = SearchType->isDependentType();
138 assert((isDependent || !SearchType->isIncompleteType()) &&
139 "Caller should have completed object type");
143 // Perform lookup into the current scope (only).
147 TypeDecl *NonMatchingTypeDecl = 0;
148 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
149 for (unsigned Step = 0; Step != 2; ++Step) {
150 // Look for the name first in the computed lookup context (if we
151 // have one) and, if that fails to find a match, in the scope (if
152 // we're allowed to look there).
154 if (Step == 0 && LookupCtx)
155 LookupQualifiedName(Found, LookupCtx);
156 else if (Step == 1 && LookInScope && S)
157 LookupName(Found, S);
161 // FIXME: Should we be suppressing ambiguities here?
162 if (Found.isAmbiguous())
165 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
166 QualType T = Context.getTypeDeclType(Type);
168 if (SearchType.isNull() || SearchType->isDependentType() ||
169 Context.hasSameUnqualifiedType(T, SearchType)) {
170 // We found our type!
172 return ParsedType::make(T);
175 if (!SearchType.isNull())
176 NonMatchingTypeDecl = Type;
179 // If the name that we found is a class template name, and it is
180 // the same name as the template name in the last part of the
181 // nested-name-specifier (if present) or the object type, then
182 // this is the destructor for that class.
183 // FIXME: This is a workaround until we get real drafting for core
184 // issue 399, for which there isn't even an obvious direction.
185 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
186 QualType MemberOfType;
188 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
189 // Figure out the type of the context, if it has one.
190 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
191 MemberOfType = Context.getTypeDeclType(Record);
194 if (MemberOfType.isNull())
195 MemberOfType = SearchType;
197 if (MemberOfType.isNull())
200 // We're referring into a class template specialization. If the
201 // class template we found is the same as the template being
202 // specialized, we found what we are looking for.
203 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
204 if (ClassTemplateSpecializationDecl *Spec
205 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
206 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
207 Template->getCanonicalDecl())
208 return ParsedType::make(MemberOfType);
214 // We're referring to an unresolved class template
215 // specialization. Determine whether we class template we found
216 // is the same as the template being specialized or, if we don't
217 // know which template is being specialized, that it at least
218 // has the same name.
219 if (const TemplateSpecializationType *SpecType
220 = MemberOfType->getAs<TemplateSpecializationType>()) {
221 TemplateName SpecName = SpecType->getTemplateName();
223 // The class template we found is the same template being
225 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
226 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
227 return ParsedType::make(MemberOfType);
232 // The class template we found has the same name as the
233 // (dependent) template name being specialized.
234 if (DependentTemplateName *DepTemplate
235 = SpecName.getAsDependentTemplateName()) {
236 if (DepTemplate->isIdentifier() &&
237 DepTemplate->getIdentifier() == Template->getIdentifier())
238 return ParsedType::make(MemberOfType);
247 // We didn't find our type, but that's okay: it's dependent
250 // FIXME: What if we have no nested-name-specifier?
251 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
252 SS.getWithLocInContext(Context),
254 return ParsedType::make(T);
257 if (NonMatchingTypeDecl) {
258 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
259 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
261 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
263 } else if (ObjectTypePtr)
264 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
267 Diag(NameLoc, diag::err_destructor_class_name);
272 ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
273 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
275 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
276 && "only get destructor types from declspecs");
277 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
278 QualType SearchType = GetTypeFromParser(ObjectType);
279 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
280 return ParsedType::make(T);
283 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
288 /// \brief Build a C++ typeid expression with a type operand.
289 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
290 SourceLocation TypeidLoc,
291 TypeSourceInfo *Operand,
292 SourceLocation RParenLoc) {
293 // C++ [expr.typeid]p4:
294 // The top-level cv-qualifiers of the lvalue expression or the type-id
295 // that is the operand of typeid are always ignored.
296 // If the type of the type-id is a class type or a reference to a class
297 // type, the class shall be completely-defined.
300 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
302 if (T->getAs<RecordType>() &&
303 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
306 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
308 SourceRange(TypeidLoc, RParenLoc)));
311 /// \brief Build a C++ typeid expression with an expression operand.
312 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
313 SourceLocation TypeidLoc,
315 SourceLocation RParenLoc) {
316 if (E && !E->isTypeDependent()) {
317 if (E->getType()->isPlaceholderType()) {
318 ExprResult result = CheckPlaceholderExpr(E);
319 if (result.isInvalid()) return ExprError();
323 QualType T = E->getType();
324 if (const RecordType *RecordT = T->getAs<RecordType>()) {
325 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
326 // C++ [expr.typeid]p3:
327 // [...] If the type of the expression is a class type, the class
328 // shall be completely-defined.
329 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
332 // C++ [expr.typeid]p3:
333 // When typeid is applied to an expression other than an glvalue of a
334 // polymorphic class type [...] [the] expression is an unevaluated
336 if (RecordD->isPolymorphic() && E->isGLValue()) {
337 // The subexpression is potentially evaluated; switch the context
338 // and recheck the subexpression.
339 ExprResult Result = TranformToPotentiallyEvaluated(E);
340 if (Result.isInvalid()) return ExprError();
343 // We require a vtable to query the type at run time.
344 MarkVTableUsed(TypeidLoc, RecordD);
348 // C++ [expr.typeid]p4:
349 // [...] If the type of the type-id is a reference to a possibly
350 // cv-qualified type, the result of the typeid expression refers to a
351 // std::type_info object representing the cv-unqualified referenced
354 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
355 if (!Context.hasSameType(T, UnqualT)) {
357 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
361 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
363 SourceRange(TypeidLoc, RParenLoc)));
366 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
368 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
369 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
370 // Find the std::type_info type.
371 if (!getStdNamespace())
372 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
374 if (!CXXTypeInfoDecl) {
375 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
376 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
377 LookupQualifiedName(R, getStdNamespace());
378 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
379 // Microsoft's typeinfo doesn't have type_info in std but in the global
380 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
381 if (!CXXTypeInfoDecl && LangOpts.MicrosoftMode) {
382 LookupQualifiedName(R, Context.getTranslationUnitDecl());
383 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
385 if (!CXXTypeInfoDecl)
386 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
389 if (!getLangOpts().RTTI) {
390 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
393 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
396 // The operand is a type; handle it as such.
397 TypeSourceInfo *TInfo = 0;
398 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
404 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
406 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
409 // The operand is an expression.
410 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
413 /// \brief Build a Microsoft __uuidof expression with a type operand.
414 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
415 SourceLocation TypeidLoc,
416 TypeSourceInfo *Operand,
417 SourceLocation RParenLoc) {
418 if (!Operand->getType()->isDependentType()) {
419 if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType()))
420 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
423 // FIXME: add __uuidof semantic analysis for type operand.
424 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
426 SourceRange(TypeidLoc, RParenLoc)));
429 /// \brief Build a Microsoft __uuidof expression with an expression operand.
430 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
431 SourceLocation TypeidLoc,
433 SourceLocation RParenLoc) {
434 if (!E->getType()->isDependentType()) {
435 if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType()) &&
436 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
437 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
439 // FIXME: add __uuidof semantic analysis for type operand.
440 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
442 SourceRange(TypeidLoc, RParenLoc)));
445 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
447 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
448 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
449 // If MSVCGuidDecl has not been cached, do the lookup.
451 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
452 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
453 LookupQualifiedName(R, Context.getTranslationUnitDecl());
454 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
456 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
459 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
462 // The operand is a type; handle it as such.
463 TypeSourceInfo *TInfo = 0;
464 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
470 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
472 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
475 // The operand is an expression.
476 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
479 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
481 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
482 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
483 "Unknown C++ Boolean value!");
484 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
485 Context.BoolTy, OpLoc));
488 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
490 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
491 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
494 /// ActOnCXXThrow - Parse throw expressions.
496 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
497 bool IsThrownVarInScope = false;
499 // C++0x [class.copymove]p31:
500 // When certain criteria are met, an implementation is allowed to omit the
501 // copy/move construction of a class object [...]
503 // - in a throw-expression, when the operand is the name of a
504 // non-volatile automatic object (other than a function or catch-
505 // clause parameter) whose scope does not extend beyond the end of the
506 // innermost enclosing try-block (if there is one), the copy/move
507 // operation from the operand to the exception object (15.1) can be
508 // omitted by constructing the automatic object directly into the
510 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
511 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
512 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
513 for( ; S; S = S->getParent()) {
514 if (S->isDeclScope(Var)) {
515 IsThrownVarInScope = true;
520 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
521 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
529 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
532 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
533 bool IsThrownVarInScope) {
534 // Don't report an error if 'throw' is used in system headers.
535 if (!getLangOpts().CXXExceptions &&
536 !getSourceManager().isInSystemHeader(OpLoc))
537 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
539 if (Ex && !Ex->isTypeDependent()) {
540 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
541 if (ExRes.isInvalid())
546 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
547 IsThrownVarInScope));
550 /// CheckCXXThrowOperand - Validate the operand of a throw.
551 ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
552 bool IsThrownVarInScope) {
553 // C++ [except.throw]p3:
554 // A throw-expression initializes a temporary object, called the exception
555 // object, the type of which is determined by removing any top-level
556 // cv-qualifiers from the static type of the operand of throw and adjusting
557 // the type from "array of T" or "function returning T" to "pointer to T"
558 // or "pointer to function returning T", [...]
559 if (E->getType().hasQualifiers())
560 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
561 E->getValueKind()).take();
563 ExprResult Res = DefaultFunctionArrayConversion(E);
568 // If the type of the exception would be an incomplete type or a pointer
569 // to an incomplete type other than (cv) void the program is ill-formed.
570 QualType Ty = E->getType();
571 bool isPointer = false;
572 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
573 Ty = Ptr->getPointeeType();
576 if (!isPointer || !Ty->isVoidType()) {
577 if (RequireCompleteType(ThrowLoc, Ty,
578 isPointer? diag::err_throw_incomplete_ptr
579 : diag::err_throw_incomplete,
580 E->getSourceRange()))
583 if (RequireNonAbstractType(ThrowLoc, E->getType(),
584 diag::err_throw_abstract_type, E))
588 // Initialize the exception result. This implicitly weeds out
589 // abstract types or types with inaccessible copy constructors.
591 // C++0x [class.copymove]p31:
592 // When certain criteria are met, an implementation is allowed to omit the
593 // copy/move construction of a class object [...]
595 // - in a throw-expression, when the operand is the name of a
596 // non-volatile automatic object (other than a function or catch-clause
597 // parameter) whose scope does not extend beyond the end of the
598 // innermost enclosing try-block (if there is one), the copy/move
599 // operation from the operand to the exception object (15.1) can be
600 // omitted by constructing the automatic object directly into the
602 const VarDecl *NRVOVariable = 0;
603 if (IsThrownVarInScope)
604 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
606 InitializedEntity Entity =
607 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
608 /*NRVO=*/NRVOVariable != 0);
609 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
616 // If the exception has class type, we need additional handling.
617 const RecordType *RecordTy = Ty->getAs<RecordType>();
620 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
622 // If we are throwing a polymorphic class type or pointer thereof,
623 // exception handling will make use of the vtable.
624 MarkVTableUsed(ThrowLoc, RD);
626 // If a pointer is thrown, the referenced object will not be destroyed.
630 // If the class has a destructor, we must be able to call it.
631 if (RD->hasIrrelevantDestructor())
634 CXXDestructorDecl *Destructor = LookupDestructor(RD);
638 MarkFunctionReferenced(E->getExprLoc(), Destructor);
639 CheckDestructorAccess(E->getExprLoc(), Destructor,
640 PDiag(diag::err_access_dtor_exception) << Ty);
641 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
645 QualType Sema::getCurrentThisType() {
646 DeclContext *DC = getFunctionLevelDeclContext();
647 QualType ThisTy = CXXThisTypeOverride;
648 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
649 if (method && method->isInstance())
650 ThisTy = method->getThisType(Context);
656 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
658 unsigned CXXThisTypeQuals,
660 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
662 if (!Enabled || !ContextDecl)
665 CXXRecordDecl *Record = 0;
666 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
667 Record = Template->getTemplatedDecl();
669 Record = cast<CXXRecordDecl>(ContextDecl);
671 S.CXXThisTypeOverride
672 = S.Context.getPointerType(
673 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
675 this->Enabled = true;
679 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
681 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
685 void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
686 // We don't need to capture this in an unevaluated context.
687 if (ExprEvalContexts.back().Context == Unevaluated && !Explicit)
690 // Otherwise, check that we can capture 'this'.
691 unsigned NumClosures = 0;
692 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
693 if (CapturingScopeInfo *CSI =
694 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
695 if (CSI->CXXThisCaptureIndex != 0) {
696 // 'this' is already being captured; there isn't anything more to do.
700 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
701 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
702 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
704 // This closure can capture 'this'; continue looking upwards.
709 // This context can't implicitly capture 'this'; fail out.
710 Diag(Loc, diag::err_this_capture) << Explicit;
716 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
717 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
719 for (unsigned idx = FunctionScopes.size() - 1;
720 NumClosures; --idx, --NumClosures) {
721 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
723 QualType ThisTy = getCurrentThisType();
724 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
725 // For lambda expressions, build a field and an initializing expression.
726 CXXRecordDecl *Lambda = LSI->Lambda;
728 = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
729 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
730 0, false, ICIS_NoInit);
731 Field->setImplicit(true);
732 Field->setAccess(AS_private);
733 Lambda->addDecl(Field);
734 ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true);
736 bool isNested = NumClosures > 1;
737 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
741 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
742 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
743 /// is a non-lvalue expression whose value is the address of the object for
744 /// which the function is called.
746 QualType ThisTy = getCurrentThisType();
747 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
749 CheckCXXThisCapture(Loc);
750 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
753 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
754 // If we're outside the body of a member function, then we'll have a specified
756 if (CXXThisTypeOverride.isNull())
759 // Determine whether we're looking into a class that's currently being
761 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
762 return Class && Class->isBeingDefined();
766 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
767 SourceLocation LParenLoc,
769 SourceLocation RParenLoc) {
773 TypeSourceInfo *TInfo;
774 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
776 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
778 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
781 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
782 /// Can be interpreted either as function-style casting ("int(x)")
783 /// or class type construction ("ClassType(x,y,z)")
784 /// or creation of a value-initialized type ("int()").
786 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
787 SourceLocation LParenLoc,
789 SourceLocation RParenLoc) {
790 QualType Ty = TInfo->getType();
791 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
793 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(exprs)) {
794 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
800 unsigned NumExprs = exprs.size();
801 Expr **Exprs = exprs.data();
803 bool ListInitialization = LParenLoc.isInvalid();
804 assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0])))
805 && "List initialization must have initializer list as expression.");
806 SourceRange FullRange = SourceRange(TyBeginLoc,
807 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
809 // C++ [expr.type.conv]p1:
810 // If the expression list is a single expression, the type conversion
811 // expression is equivalent (in definedness, and if defined in meaning) to the
812 // corresponding cast expression.
813 if (NumExprs == 1 && !ListInitialization) {
814 Expr *Arg = Exprs[0];
815 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
818 QualType ElemTy = Ty;
819 if (Ty->isArrayType()) {
820 if (!ListInitialization)
821 return ExprError(Diag(TyBeginLoc,
822 diag::err_value_init_for_array_type) << FullRange);
823 ElemTy = Context.getBaseElementType(Ty);
826 if (!Ty->isVoidType() &&
827 RequireCompleteType(TyBeginLoc, ElemTy,
828 diag::err_invalid_incomplete_type_use, FullRange))
831 if (RequireNonAbstractType(TyBeginLoc, Ty,
832 diag::err_allocation_of_abstract_type))
835 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
836 InitializationKind Kind
837 = NumExprs ? ListInitialization
838 ? InitializationKind::CreateDirectList(TyBeginLoc)
839 : InitializationKind::CreateDirect(TyBeginLoc,
840 LParenLoc, RParenLoc)
841 : InitializationKind::CreateValue(TyBeginLoc,
842 LParenLoc, RParenLoc);
843 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
844 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, exprs);
846 if (!Result.isInvalid() && ListInitialization &&
847 isa<InitListExpr>(Result.get())) {
848 // If the list-initialization doesn't involve a constructor call, we'll get
849 // the initializer-list (with corrected type) back, but that's not what we
850 // want, since it will be treated as an initializer list in further
851 // processing. Explicitly insert a cast here.
852 InitListExpr *List = cast<InitListExpr>(Result.take());
853 Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(),
854 Expr::getValueKindForType(TInfo->getType()),
855 TInfo, TyBeginLoc, CK_NoOp,
856 List, /*Path=*/0, RParenLoc));
859 // FIXME: Improve AST representation?
863 /// doesUsualArrayDeleteWantSize - Answers whether the usual
864 /// operator delete[] for the given type has a size_t parameter.
865 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
866 QualType allocType) {
867 const RecordType *record =
868 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
869 if (!record) return false;
871 // Try to find an operator delete[] in class scope.
873 DeclarationName deleteName =
874 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
875 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
876 S.LookupQualifiedName(ops, record->getDecl());
878 // We're just doing this for information.
879 ops.suppressDiagnostics();
881 // Very likely: there's no operator delete[].
882 if (ops.empty()) return false;
884 // If it's ambiguous, it should be illegal to call operator delete[]
885 // on this thing, so it doesn't matter if we allocate extra space or not.
886 if (ops.isAmbiguous()) return false;
888 LookupResult::Filter filter = ops.makeFilter();
889 while (filter.hasNext()) {
890 NamedDecl *del = filter.next()->getUnderlyingDecl();
892 // C++0x [basic.stc.dynamic.deallocation]p2:
893 // A template instance is never a usual deallocation function,
894 // regardless of its signature.
895 if (isa<FunctionTemplateDecl>(del)) {
900 // C++0x [basic.stc.dynamic.deallocation]p2:
901 // If class T does not declare [an operator delete[] with one
902 // parameter] but does declare a member deallocation function
903 // named operator delete[] with exactly two parameters, the
904 // second of which has type std::size_t, then this function
905 // is a usual deallocation function.
906 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
913 if (!ops.isSingleResult()) return false;
915 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
916 return (del->getNumParams() == 2);
919 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
922 /// @code new (memory) int[size][4] @endcode
924 /// @code ::new Foo(23, "hello") @endcode
926 /// \param StartLoc The first location of the expression.
927 /// \param UseGlobal True if 'new' was prefixed with '::'.
928 /// \param PlacementLParen Opening paren of the placement arguments.
929 /// \param PlacementArgs Placement new arguments.
930 /// \param PlacementRParen Closing paren of the placement arguments.
931 /// \param TypeIdParens If the type is in parens, the source range.
932 /// \param D The type to be allocated, as well as array dimensions.
933 /// \param Initializer The initializing expression or initializer-list, or null
934 /// if there is none.
936 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
937 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
938 SourceLocation PlacementRParen, SourceRange TypeIdParens,
939 Declarator &D, Expr *Initializer) {
940 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
943 // If the specified type is an array, unwrap it and save the expression.
944 if (D.getNumTypeObjects() > 0 &&
945 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
946 DeclaratorChunk &Chunk = D.getTypeObject(0);
947 if (TypeContainsAuto)
948 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
949 << D.getSourceRange());
950 if (Chunk.Arr.hasStatic)
951 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
952 << D.getSourceRange());
953 if (!Chunk.Arr.NumElts)
954 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
955 << D.getSourceRange());
957 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
958 D.DropFirstTypeObject();
961 // Every dimension shall be of constant size.
963 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
964 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
967 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
968 if (Expr *NumElts = (Expr *)Array.NumElts) {
969 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
971 = VerifyIntegerConstantExpression(NumElts, 0,
972 diag::err_new_array_nonconst)
981 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
982 QualType AllocType = TInfo->getType();
983 if (D.isInvalidType())
986 SourceRange DirectInitRange;
987 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
988 DirectInitRange = List->getSourceRange();
990 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1003 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1007 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1008 return PLE->getNumExprs() == 0;
1009 if (isa<ImplicitValueInitExpr>(Init))
1011 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1012 return !CCE->isListInitialization() &&
1013 CCE->getConstructor()->isDefaultConstructor();
1014 else if (Style == CXXNewExpr::ListInit) {
1015 assert(isa<InitListExpr>(Init) &&
1016 "Shouldn't create list CXXConstructExprs for arrays.");
1023 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1024 SourceLocation PlacementLParen,
1025 MultiExprArg PlacementArgs,
1026 SourceLocation PlacementRParen,
1027 SourceRange TypeIdParens,
1029 TypeSourceInfo *AllocTypeInfo,
1031 SourceRange DirectInitRange,
1033 bool TypeMayContainAuto) {
1034 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1035 SourceLocation StartLoc = Range.getBegin();
1037 CXXNewExpr::InitializationStyle initStyle;
1038 if (DirectInitRange.isValid()) {
1039 assert(Initializer && "Have parens but no initializer.");
1040 initStyle = CXXNewExpr::CallInit;
1041 } else if (Initializer && isa<InitListExpr>(Initializer))
1042 initStyle = CXXNewExpr::ListInit;
1044 // In template instantiation, the initializer could be a CXXDefaultArgExpr
1045 // unwrapped from a CXXConstructExpr that was implicitly built. There is no
1046 // particularly sane way we can handle this (especially since it can even
1047 // occur for array new), so we throw the initializer away and have it be
1049 if (Initializer && isa<CXXDefaultArgExpr>(Initializer))
1051 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1052 isa<CXXConstructExpr>(Initializer)) &&
1053 "Initializer expression that cannot have been implicitly created.");
1054 initStyle = CXXNewExpr::NoInit;
1057 Expr **Inits = &Initializer;
1058 unsigned NumInits = Initializer ? 1 : 0;
1059 if (initStyle == CXXNewExpr::CallInit) {
1060 if (ParenListExpr *List = dyn_cast<ParenListExpr>(Initializer)) {
1061 Inits = List->getExprs();
1062 NumInits = List->getNumExprs();
1063 } else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Initializer)){
1064 if (!isa<CXXTemporaryObjectExpr>(CCE)) {
1065 // Can happen in template instantiation. Since this is just an implicit
1066 // construction, we just take it apart and rebuild it.
1067 Inits = CCE->getArgs();
1068 NumInits = CCE->getNumArgs();
1073 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1075 if (TypeMayContainAuto &&
1076 (AT = AllocType->getContainedAutoType()) && !AT->isDeduced()) {
1077 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1078 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1079 << AllocType << TypeRange);
1080 if (initStyle == CXXNewExpr::ListInit)
1081 return ExprError(Diag(Inits[0]->getLocStart(),
1082 diag::err_auto_new_requires_parens)
1083 << AllocType << TypeRange);
1085 Expr *FirstBad = Inits[1];
1086 return ExprError(Diag(FirstBad->getLocStart(),
1087 diag::err_auto_new_ctor_multiple_expressions)
1088 << AllocType << TypeRange);
1090 Expr *Deduce = Inits[0];
1091 TypeSourceInfo *DeducedType = 0;
1092 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1093 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1094 << AllocType << Deduce->getType()
1095 << TypeRange << Deduce->getSourceRange());
1099 AllocTypeInfo = DeducedType;
1100 AllocType = AllocTypeInfo->getType();
1103 // Per C++0x [expr.new]p5, the type being constructed may be a
1104 // typedef of an array type.
1106 if (const ConstantArrayType *Array
1107 = Context.getAsConstantArrayType(AllocType)) {
1108 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1109 Context.getSizeType(),
1110 TypeRange.getEnd());
1111 AllocType = Array->getElementType();
1115 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1118 if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
1119 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1120 diag::warn_dangling_std_initializer_list)
1121 << /*at end of FE*/0 << Inits[0]->getSourceRange();
1124 // In ARC, infer 'retaining' for the allocated
1125 if (getLangOpts().ObjCAutoRefCount &&
1126 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1127 AllocType->isObjCLifetimeType()) {
1128 AllocType = Context.getLifetimeQualifiedType(AllocType,
1129 AllocType->getObjCARCImplicitLifetime());
1132 QualType ResultType = Context.getPointerType(AllocType);
1134 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1135 // integral or enumeration type with a non-negative value."
1136 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1137 // enumeration type, or a class type for which a single non-explicit
1138 // conversion function to integral or unscoped enumeration type exists.
1139 if (ArraySize && !ArraySize->isTypeDependent()) {
1140 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1144 SizeConvertDiagnoser(Expr *ArraySize)
1145 : ICEConvertDiagnoser(false, false), ArraySize(ArraySize) { }
1147 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1149 return S.Diag(Loc, diag::err_array_size_not_integral)
1150 << S.getLangOpts().CPlusPlus0x << T;
1153 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
1155 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1156 << T << ArraySize->getSourceRange();
1159 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
1163 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1166 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
1167 CXXConversionDecl *Conv,
1169 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1170 << ConvTy->isEnumeralType() << ConvTy;
1173 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
1175 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1178 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
1180 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1181 << ConvTy->isEnumeralType() << ConvTy;
1184 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1188 S.getLangOpts().CPlusPlus0x
1189 ? diag::warn_cxx98_compat_array_size_conversion
1190 : diag::ext_array_size_conversion)
1191 << T << ConvTy->isEnumeralType() << ConvTy;
1193 } SizeDiagnoser(ArraySize);
1195 ExprResult ConvertedSize
1196 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize, SizeDiagnoser,
1197 /*AllowScopedEnumerations*/ false);
1198 if (ConvertedSize.isInvalid())
1201 ArraySize = ConvertedSize.take();
1202 QualType SizeType = ArraySize->getType();
1203 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1206 // C++98 [expr.new]p7:
1207 // The expression in a direct-new-declarator shall have integral type
1208 // with a non-negative value.
1210 // Let's see if this is a constant < 0. If so, we reject it out of
1211 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1214 // Note: such a construct has well-defined semantics in C++11: it throws
1215 // std::bad_array_new_length.
1216 if (!ArraySize->isValueDependent()) {
1218 // We've already performed any required implicit conversion to integer or
1219 // unscoped enumeration type.
1220 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1221 if (Value < llvm::APSInt(
1222 llvm::APInt::getNullValue(Value.getBitWidth()),
1223 Value.isUnsigned())) {
1224 if (getLangOpts().CPlusPlus0x)
1225 Diag(ArraySize->getLocStart(),
1226 diag::warn_typecheck_negative_array_new_size)
1227 << ArraySize->getSourceRange();
1229 return ExprError(Diag(ArraySize->getLocStart(),
1230 diag::err_typecheck_negative_array_size)
1231 << ArraySize->getSourceRange());
1232 } else if (!AllocType->isDependentType()) {
1233 unsigned ActiveSizeBits =
1234 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1235 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1236 if (getLangOpts().CPlusPlus0x)
1237 Diag(ArraySize->getLocStart(),
1238 diag::warn_array_new_too_large)
1239 << Value.toString(10)
1240 << ArraySize->getSourceRange();
1242 return ExprError(Diag(ArraySize->getLocStart(),
1243 diag::err_array_too_large)
1244 << Value.toString(10)
1245 << ArraySize->getSourceRange());
1248 } else if (TypeIdParens.isValid()) {
1249 // Can't have dynamic array size when the type-id is in parentheses.
1250 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1251 << ArraySize->getSourceRange()
1252 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1253 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1255 TypeIdParens = SourceRange();
1259 // Note that we do *not* convert the argument in any way. It can
1260 // be signed, larger than size_t, whatever.
1263 FunctionDecl *OperatorNew = 0;
1264 FunctionDecl *OperatorDelete = 0;
1265 Expr **PlaceArgs = PlacementArgs.data();
1266 unsigned NumPlaceArgs = PlacementArgs.size();
1268 if (!AllocType->isDependentType() &&
1269 !Expr::hasAnyTypeDependentArguments(
1270 llvm::makeArrayRef(PlaceArgs, NumPlaceArgs)) &&
1271 FindAllocationFunctions(StartLoc,
1272 SourceRange(PlacementLParen, PlacementRParen),
1273 UseGlobal, AllocType, ArraySize, PlaceArgs,
1274 NumPlaceArgs, OperatorNew, OperatorDelete))
1277 // If this is an array allocation, compute whether the usual array
1278 // deallocation function for the type has a size_t parameter.
1279 bool UsualArrayDeleteWantsSize = false;
1280 if (ArraySize && !AllocType->isDependentType())
1281 UsualArrayDeleteWantsSize
1282 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1284 SmallVector<Expr *, 8> AllPlaceArgs;
1286 // Add default arguments, if any.
1287 const FunctionProtoType *Proto =
1288 OperatorNew->getType()->getAs<FunctionProtoType>();
1289 VariadicCallType CallType =
1290 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
1292 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
1293 Proto, 1, PlaceArgs, NumPlaceArgs,
1294 AllPlaceArgs, CallType))
1297 NumPlaceArgs = AllPlaceArgs.size();
1298 if (NumPlaceArgs > 0)
1299 PlaceArgs = &AllPlaceArgs[0];
1301 DiagnoseSentinelCalls(OperatorNew, PlacementLParen,
1302 PlaceArgs, NumPlaceArgs);
1304 // FIXME: Missing call to CheckFunctionCall or equivalent
1307 // Warn if the type is over-aligned and is being allocated by global operator
1309 if (NumPlaceArgs == 0 && OperatorNew &&
1310 (OperatorNew->isImplicit() ||
1311 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1312 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1313 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1314 if (Align > SuitableAlign)
1315 Diag(StartLoc, diag::warn_overaligned_type)
1317 << unsigned(Align / Context.getCharWidth())
1318 << unsigned(SuitableAlign / Context.getCharWidth());
1322 QualType InitType = AllocType;
1323 // Array 'new' can't have any initializers except empty parentheses.
1324 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1325 // dialect distinction.
1326 if (ResultType->isArrayType() || ArraySize) {
1327 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1328 SourceRange InitRange(Inits[0]->getLocStart(),
1329 Inits[NumInits - 1]->getLocEnd());
1330 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1333 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1334 // We do the initialization typechecking against the array type
1335 // corresponding to the number of initializers + 1 (to also check
1336 // default-initialization).
1337 unsigned NumElements = ILE->getNumInits() + 1;
1338 InitType = Context.getConstantArrayType(AllocType,
1339 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1340 ArrayType::Normal, 0);
1344 if (!AllocType->isDependentType() &&
1345 !Expr::hasAnyTypeDependentArguments(
1346 llvm::makeArrayRef(Inits, NumInits))) {
1347 // C++11 [expr.new]p15:
1348 // A new-expression that creates an object of type T initializes that
1349 // object as follows:
1350 InitializationKind Kind
1351 // - If the new-initializer is omitted, the object is default-
1352 // initialized (8.5); if no initialization is performed,
1353 // the object has indeterminate value
1354 = initStyle == CXXNewExpr::NoInit
1355 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1356 // - Otherwise, the new-initializer is interpreted according to the
1357 // initialization rules of 8.5 for direct-initialization.
1358 : initStyle == CXXNewExpr::ListInit
1359 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1360 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1361 DirectInitRange.getBegin(),
1362 DirectInitRange.getEnd());
1364 InitializedEntity Entity
1365 = InitializedEntity::InitializeNew(StartLoc, InitType);
1366 InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits);
1367 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1368 MultiExprArg(Inits, NumInits));
1369 if (FullInit.isInvalid())
1372 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1373 // we don't want the initialized object to be destructed.
1374 if (CXXBindTemporaryExpr *Binder =
1375 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1376 FullInit = Owned(Binder->getSubExpr());
1378 Initializer = FullInit.take();
1381 // Mark the new and delete operators as referenced.
1383 MarkFunctionReferenced(StartLoc, OperatorNew);
1385 MarkFunctionReferenced(StartLoc, OperatorDelete);
1387 // C++0x [expr.new]p17:
1388 // If the new expression creates an array of objects of class type,
1389 // access and ambiguity control are done for the destructor.
1390 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1391 if (ArraySize && !BaseAllocType->isDependentType()) {
1392 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1393 if (CXXDestructorDecl *dtor = LookupDestructor(
1394 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1395 MarkFunctionReferenced(StartLoc, dtor);
1396 CheckDestructorAccess(StartLoc, dtor,
1397 PDiag(diag::err_access_dtor)
1399 DiagnoseUseOfDecl(dtor, StartLoc);
1404 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1406 UsualArrayDeleteWantsSize,
1407 llvm::makeArrayRef(PlaceArgs, NumPlaceArgs),
1409 ArraySize, initStyle, Initializer,
1410 ResultType, AllocTypeInfo,
1411 Range, DirectInitRange));
1414 /// \brief Checks that a type is suitable as the allocated type
1415 /// in a new-expression.
1416 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1418 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1419 // abstract class type or array thereof.
1420 if (AllocType->isFunctionType())
1421 return Diag(Loc, diag::err_bad_new_type)
1422 << AllocType << 0 << R;
1423 else if (AllocType->isReferenceType())
1424 return Diag(Loc, diag::err_bad_new_type)
1425 << AllocType << 1 << R;
1426 else if (!AllocType->isDependentType() &&
1427 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
1429 else if (RequireNonAbstractType(Loc, AllocType,
1430 diag::err_allocation_of_abstract_type))
1432 else if (AllocType->isVariablyModifiedType())
1433 return Diag(Loc, diag::err_variably_modified_new_type)
1435 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1436 return Diag(Loc, diag::err_address_space_qualified_new)
1437 << AllocType.getUnqualifiedType() << AddressSpace;
1438 else if (getLangOpts().ObjCAutoRefCount) {
1439 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1440 QualType BaseAllocType = Context.getBaseElementType(AT);
1441 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1442 BaseAllocType->isObjCLifetimeType())
1443 return Diag(Loc, diag::err_arc_new_array_without_ownership)
1451 /// \brief Determine whether the given function is a non-placement
1452 /// deallocation function.
1453 static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1454 if (FD->isInvalidDecl())
1457 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1458 return Method->isUsualDeallocationFunction();
1460 return ((FD->getOverloadedOperator() == OO_Delete ||
1461 FD->getOverloadedOperator() == OO_Array_Delete) &&
1462 FD->getNumParams() == 1);
1465 /// FindAllocationFunctions - Finds the overloads of operator new and delete
1466 /// that are appropriate for the allocation.
1467 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1468 bool UseGlobal, QualType AllocType,
1469 bool IsArray, Expr **PlaceArgs,
1470 unsigned NumPlaceArgs,
1471 FunctionDecl *&OperatorNew,
1472 FunctionDecl *&OperatorDelete) {
1473 // --- Choosing an allocation function ---
1474 // C++ 5.3.4p8 - 14 & 18
1475 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1476 // in the scope of the allocated class.
1477 // 2) If an array size is given, look for operator new[], else look for
1479 // 3) The first argument is always size_t. Append the arguments from the
1482 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1483 // We don't care about the actual value of this argument.
1484 // FIXME: Should the Sema create the expression and embed it in the syntax
1485 // tree? Or should the consumer just recalculate the value?
1486 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1487 Context.getTargetInfo().getPointerWidth(0)),
1488 Context.getSizeType(),
1490 AllocArgs[0] = &Size;
1491 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1493 // C++ [expr.new]p8:
1494 // If the allocated type is a non-array type, the allocation
1495 // function's name is operator new and the deallocation function's
1496 // name is operator delete. If the allocated type is an array
1497 // type, the allocation function's name is operator new[] and the
1498 // deallocation function's name is operator delete[].
1499 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1500 IsArray ? OO_Array_New : OO_New);
1501 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1502 IsArray ? OO_Array_Delete : OO_Delete);
1504 QualType AllocElemType = Context.getBaseElementType(AllocType);
1506 if (AllocElemType->isRecordType() && !UseGlobal) {
1507 CXXRecordDecl *Record
1508 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1509 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1510 AllocArgs.size(), Record, /*AllowMissing=*/true,
1515 // Didn't find a member overload. Look for a global one.
1516 DeclareGlobalNewDelete();
1517 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1518 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1519 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1524 // We don't need an operator delete if we're running under
1526 if (!getLangOpts().Exceptions) {
1531 // FindAllocationOverload can change the passed in arguments, so we need to
1533 if (NumPlaceArgs > 0)
1534 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
1536 // C++ [expr.new]p19:
1538 // If the new-expression begins with a unary :: operator, the
1539 // deallocation function's name is looked up in the global
1540 // scope. Otherwise, if the allocated type is a class type T or an
1541 // array thereof, the deallocation function's name is looked up in
1542 // the scope of T. If this lookup fails to find the name, or if
1543 // the allocated type is not a class type or array thereof, the
1544 // deallocation function's name is looked up in the global scope.
1545 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1546 if (AllocElemType->isRecordType() && !UseGlobal) {
1548 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1549 LookupQualifiedName(FoundDelete, RD);
1551 if (FoundDelete.isAmbiguous())
1552 return true; // FIXME: clean up expressions?
1554 if (FoundDelete.empty()) {
1555 DeclareGlobalNewDelete();
1556 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1559 FoundDelete.suppressDiagnostics();
1561 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1563 // Whether we're looking for a placement operator delete is dictated
1564 // by whether we selected a placement operator new, not by whether
1565 // we had explicit placement arguments. This matters for things like
1566 // struct A { void *operator new(size_t, int = 0); ... };
1568 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1570 if (isPlacementNew) {
1571 // C++ [expr.new]p20:
1572 // A declaration of a placement deallocation function matches the
1573 // declaration of a placement allocation function if it has the
1574 // same number of parameters and, after parameter transformations
1575 // (8.3.5), all parameter types except the first are
1578 // To perform this comparison, we compute the function type that
1579 // the deallocation function should have, and use that type both
1580 // for template argument deduction and for comparison purposes.
1582 // FIXME: this comparison should ignore CC and the like.
1583 QualType ExpectedFunctionType;
1585 const FunctionProtoType *Proto
1586 = OperatorNew->getType()->getAs<FunctionProtoType>();
1588 SmallVector<QualType, 4> ArgTypes;
1589 ArgTypes.push_back(Context.VoidPtrTy);
1590 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1591 ArgTypes.push_back(Proto->getArgType(I));
1593 FunctionProtoType::ExtProtoInfo EPI;
1594 EPI.Variadic = Proto->isVariadic();
1596 ExpectedFunctionType
1597 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1598 ArgTypes.size(), EPI);
1601 for (LookupResult::iterator D = FoundDelete.begin(),
1602 DEnd = FoundDelete.end();
1604 FunctionDecl *Fn = 0;
1605 if (FunctionTemplateDecl *FnTmpl
1606 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1607 // Perform template argument deduction to try to match the
1608 // expected function type.
1609 TemplateDeductionInfo Info(StartLoc);
1610 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1613 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1615 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1616 Matches.push_back(std::make_pair(D.getPair(), Fn));
1619 // C++ [expr.new]p20:
1620 // [...] Any non-placement deallocation function matches a
1621 // non-placement allocation function. [...]
1622 for (LookupResult::iterator D = FoundDelete.begin(),
1623 DEnd = FoundDelete.end();
1625 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1626 if (isNonPlacementDeallocationFunction(Fn))
1627 Matches.push_back(std::make_pair(D.getPair(), Fn));
1631 // C++ [expr.new]p20:
1632 // [...] If the lookup finds a single matching deallocation
1633 // function, that function will be called; otherwise, no
1634 // deallocation function will be called.
1635 if (Matches.size() == 1) {
1636 OperatorDelete = Matches[0].second;
1638 // C++0x [expr.new]p20:
1639 // If the lookup finds the two-parameter form of a usual
1640 // deallocation function (3.7.4.2) and that function, considered
1641 // as a placement deallocation function, would have been
1642 // selected as a match for the allocation function, the program
1644 if (NumPlaceArgs && getLangOpts().CPlusPlus0x &&
1645 isNonPlacementDeallocationFunction(OperatorDelete)) {
1646 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1647 << SourceRange(PlaceArgs[0]->getLocStart(),
1648 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1649 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1652 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1660 /// FindAllocationOverload - Find an fitting overload for the allocation
1661 /// function in the specified scope.
1662 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1663 DeclarationName Name, Expr** Args,
1664 unsigned NumArgs, DeclContext *Ctx,
1665 bool AllowMissing, FunctionDecl *&Operator,
1667 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1668 LookupQualifiedName(R, Ctx);
1670 if (AllowMissing || !Diagnose)
1672 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1676 if (R.isAmbiguous())
1679 R.suppressDiagnostics();
1681 OverloadCandidateSet Candidates(StartLoc);
1682 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1683 Alloc != AllocEnd; ++Alloc) {
1684 // Even member operator new/delete are implicitly treated as
1685 // static, so don't use AddMemberCandidate.
1686 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1688 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1689 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1690 /*ExplicitTemplateArgs=*/0,
1691 llvm::makeArrayRef(Args, NumArgs),
1693 /*SuppressUserConversions=*/false);
1697 FunctionDecl *Fn = cast<FunctionDecl>(D);
1698 AddOverloadCandidate(Fn, Alloc.getPair(),
1699 llvm::makeArrayRef(Args, NumArgs), Candidates,
1700 /*SuppressUserConversions=*/false);
1703 // Do the resolution.
1704 OverloadCandidateSet::iterator Best;
1705 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1708 FunctionDecl *FnDecl = Best->Function;
1709 MarkFunctionReferenced(StartLoc, FnDecl);
1710 // The first argument is size_t, and the first parameter must be size_t,
1711 // too. This is checked on declaration and can be assumed. (It can't be
1712 // asserted on, though, since invalid decls are left in there.)
1713 // Watch out for variadic allocator function.
1714 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1715 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1716 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1717 FnDecl->getParamDecl(i));
1719 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1723 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
1724 if (Result.isInvalid())
1727 Args[i] = Result.takeAs<Expr>();
1732 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1733 Best->FoundDecl, Diagnose) == AR_inaccessible)
1739 case OR_No_Viable_Function:
1741 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1743 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1744 llvm::makeArrayRef(Args, NumArgs));
1750 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1752 Candidates.NoteCandidates(*this, OCD_ViableCandidates,
1753 llvm::makeArrayRef(Args, NumArgs));
1759 Diag(StartLoc, diag::err_ovl_deleted_call)
1760 << Best->Function->isDeleted()
1762 << getDeletedOrUnavailableSuffix(Best->Function)
1764 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1765 llvm::makeArrayRef(Args, NumArgs));
1770 llvm_unreachable("Unreachable, bad result from BestViableFunction");
1774 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
1775 /// delete. These are:
1778 /// void* operator new(std::size_t) throw(std::bad_alloc);
1779 /// void* operator new[](std::size_t) throw(std::bad_alloc);
1780 /// void operator delete(void *) throw();
1781 /// void operator delete[](void *) throw();
1783 /// void* operator new(std::size_t);
1784 /// void* operator new[](std::size_t);
1785 /// void operator delete(void *);
1786 /// void operator delete[](void *);
1788 /// C++0x operator delete is implicitly noexcept.
1789 /// Note that the placement and nothrow forms of new are *not* implicitly
1790 /// declared. Their use requires including \<new\>.
1791 void Sema::DeclareGlobalNewDelete() {
1792 if (GlobalNewDeleteDeclared)
1795 // C++ [basic.std.dynamic]p2:
1796 // [...] The following allocation and deallocation functions (18.4) are
1797 // implicitly declared in global scope in each translation unit of a
1801 // void* operator new(std::size_t) throw(std::bad_alloc);
1802 // void* operator new[](std::size_t) throw(std::bad_alloc);
1803 // void operator delete(void*) throw();
1804 // void operator delete[](void*) throw();
1806 // void* operator new(std::size_t);
1807 // void* operator new[](std::size_t);
1808 // void operator delete(void*);
1809 // void operator delete[](void*);
1811 // These implicit declarations introduce only the function names operator
1812 // new, operator new[], operator delete, operator delete[].
1814 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1815 // "std" or "bad_alloc" as necessary to form the exception specification.
1816 // However, we do not make these implicit declarations visible to name
1818 // Note that the C++0x versions of operator delete are deallocation functions,
1819 // and thus are implicitly noexcept.
1820 if (!StdBadAlloc && !getLangOpts().CPlusPlus0x) {
1821 // The "std::bad_alloc" class has not yet been declared, so build it
1823 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1824 getOrCreateStdNamespace(),
1825 SourceLocation(), SourceLocation(),
1826 &PP.getIdentifierTable().get("bad_alloc"),
1828 getStdBadAlloc()->setImplicit(true);
1831 GlobalNewDeleteDeclared = true;
1833 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1834 QualType SizeT = Context.getSizeType();
1835 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
1837 DeclareGlobalAllocationFunction(
1838 Context.DeclarationNames.getCXXOperatorName(OO_New),
1839 VoidPtr, SizeT, AssumeSaneOperatorNew);
1840 DeclareGlobalAllocationFunction(
1841 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1842 VoidPtr, SizeT, AssumeSaneOperatorNew);
1843 DeclareGlobalAllocationFunction(
1844 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1845 Context.VoidTy, VoidPtr);
1846 DeclareGlobalAllocationFunction(
1847 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1848 Context.VoidTy, VoidPtr);
1851 /// DeclareGlobalAllocationFunction - Declares a single implicit global
1852 /// allocation function if it doesn't already exist.
1853 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1854 QualType Return, QualType Argument,
1855 bool AddMallocAttr) {
1856 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1858 // Check if this function is already declared.
1860 DeclContext::lookup_iterator Alloc, AllocEnd;
1861 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1862 Alloc != AllocEnd; ++Alloc) {
1863 // Only look at non-template functions, as it is the predefined,
1864 // non-templated allocation function we are trying to declare here.
1865 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1866 QualType InitialParamType =
1867 Context.getCanonicalType(
1868 Func->getParamDecl(0)->getType().getUnqualifiedType());
1869 // FIXME: Do we need to check for default arguments here?
1870 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1871 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
1872 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1879 QualType BadAllocType;
1880 bool HasBadAllocExceptionSpec
1881 = (Name.getCXXOverloadedOperator() == OO_New ||
1882 Name.getCXXOverloadedOperator() == OO_Array_New);
1883 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus0x) {
1884 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1885 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
1888 FunctionProtoType::ExtProtoInfo EPI;
1889 if (HasBadAllocExceptionSpec) {
1890 if (!getLangOpts().CPlusPlus0x) {
1891 EPI.ExceptionSpecType = EST_Dynamic;
1892 EPI.NumExceptions = 1;
1893 EPI.Exceptions = &BadAllocType;
1896 EPI.ExceptionSpecType = getLangOpts().CPlusPlus0x ?
1897 EST_BasicNoexcept : EST_DynamicNone;
1900 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
1901 FunctionDecl *Alloc =
1902 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1903 SourceLocation(), Name,
1904 FnType, /*TInfo=*/0, SC_None,
1905 SC_None, false, true);
1906 Alloc->setImplicit();
1909 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1911 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1912 SourceLocation(), 0,
1913 Argument, /*TInfo=*/0,
1914 SC_None, SC_None, 0);
1915 Alloc->setParams(Param);
1917 // FIXME: Also add this declaration to the IdentifierResolver, but
1918 // make sure it is at the end of the chain to coincide with the
1920 Context.getTranslationUnitDecl()->addDecl(Alloc);
1923 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1924 DeclarationName Name,
1925 FunctionDecl* &Operator, bool Diagnose) {
1926 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1927 // Try to find operator delete/operator delete[] in class scope.
1928 LookupQualifiedName(Found, RD);
1930 if (Found.isAmbiguous())
1933 Found.suppressDiagnostics();
1935 SmallVector<DeclAccessPair,4> Matches;
1936 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1938 NamedDecl *ND = (*F)->getUnderlyingDecl();
1940 // Ignore template operator delete members from the check for a usual
1941 // deallocation function.
1942 if (isa<FunctionTemplateDecl>(ND))
1945 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
1946 Matches.push_back(F.getPair());
1949 // There's exactly one suitable operator; pick it.
1950 if (Matches.size() == 1) {
1951 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1953 if (Operator->isDeleted()) {
1955 Diag(StartLoc, diag::err_deleted_function_use);
1956 NoteDeletedFunction(Operator);
1961 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1962 Matches[0], Diagnose) == AR_inaccessible)
1967 // We found multiple suitable operators; complain about the ambiguity.
1968 } else if (!Matches.empty()) {
1970 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1973 for (SmallVectorImpl<DeclAccessPair>::iterator
1974 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1975 Diag((*F)->getUnderlyingDecl()->getLocation(),
1976 diag::note_member_declared_here) << Name;
1981 // We did find operator delete/operator delete[] declarations, but
1982 // none of them were suitable.
1983 if (!Found.empty()) {
1985 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1988 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1990 Diag((*F)->getUnderlyingDecl()->getLocation(),
1991 diag::note_member_declared_here) << Name;
1996 // Look for a global declaration.
1997 DeclareGlobalNewDelete();
1998 DeclContext *TUDecl = Context.getTranslationUnitDecl();
2000 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
2001 Expr* DeallocArgs[1];
2002 DeallocArgs[0] = &Null;
2003 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
2004 DeallocArgs, 1, TUDecl, !Diagnose,
2005 Operator, Diagnose))
2008 assert(Operator && "Did not find a deallocation function!");
2012 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2013 /// @code ::delete ptr; @endcode
2015 /// @code delete [] ptr; @endcode
2017 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
2018 bool ArrayForm, Expr *ExE) {
2019 // C++ [expr.delete]p1:
2020 // The operand shall have a pointer type, or a class type having a single
2021 // conversion function to a pointer type. The result has type void.
2023 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2025 ExprResult Ex = Owned(ExE);
2026 FunctionDecl *OperatorDelete = 0;
2027 bool ArrayFormAsWritten = ArrayForm;
2028 bool UsualArrayDeleteWantsSize = false;
2030 if (!Ex.get()->isTypeDependent()) {
2031 // Perform lvalue-to-rvalue cast, if needed.
2032 Ex = DefaultLvalueConversion(Ex.take());
2034 QualType Type = Ex.get()->getType();
2036 if (const RecordType *Record = Type->getAs<RecordType>()) {
2037 if (RequireCompleteType(StartLoc, Type,
2038 diag::err_delete_incomplete_class_type))
2041 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
2043 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2044 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
2045 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2046 E = Conversions->end(); I != E; ++I) {
2047 NamedDecl *D = I.getDecl();
2048 if (isa<UsingShadowDecl>(D))
2049 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2051 // Skip over templated conversion functions; they aren't considered.
2052 if (isa<FunctionTemplateDecl>(D))
2055 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
2057 QualType ConvType = Conv->getConversionType().getNonReferenceType();
2058 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
2059 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
2060 ObjectPtrConversions.push_back(Conv);
2062 if (ObjectPtrConversions.size() == 1) {
2063 // We have a single conversion to a pointer-to-object type. Perform
2065 // TODO: don't redo the conversion calculation.
2067 PerformImplicitConversion(Ex.get(),
2068 ObjectPtrConversions.front()->getConversionType(),
2070 if (Res.isUsable()) {
2072 Type = Ex.get()->getType();
2075 else if (ObjectPtrConversions.size() > 1) {
2076 Diag(StartLoc, diag::err_ambiguous_delete_operand)
2077 << Type << Ex.get()->getSourceRange();
2078 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
2079 NoteOverloadCandidate(ObjectPtrConversions[i]);
2084 if (!Type->isPointerType())
2085 return ExprError(Diag(StartLoc, diag::err_delete_operand)
2086 << Type << Ex.get()->getSourceRange());
2088 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
2089 QualType PointeeElem = Context.getBaseElementType(Pointee);
2091 if (unsigned AddressSpace = Pointee.getAddressSpace())
2092 return Diag(Ex.get()->getLocStart(),
2093 diag::err_address_space_qualified_delete)
2094 << Pointee.getUnqualifiedType() << AddressSpace;
2096 CXXRecordDecl *PointeeRD = 0;
2097 if (Pointee->isVoidType() && !isSFINAEContext()) {
2098 // The C++ standard bans deleting a pointer to a non-object type, which
2099 // effectively bans deletion of "void*". However, most compilers support
2100 // this, so we treat it as a warning unless we're in a SFINAE context.
2101 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
2102 << Type << Ex.get()->getSourceRange();
2103 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
2104 return ExprError(Diag(StartLoc, diag::err_delete_operand)
2105 << Type << Ex.get()->getSourceRange());
2106 } else if (!Pointee->isDependentType()) {
2107 if (!RequireCompleteType(StartLoc, Pointee,
2108 diag::warn_delete_incomplete, Ex.get())) {
2109 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2110 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2114 // C++ [expr.delete]p2:
2115 // [Note: a pointer to a const type can be the operand of a
2116 // delete-expression; it is not necessary to cast away the constness
2117 // (5.2.11) of the pointer expression before it is used as the operand
2118 // of the delete-expression. ]
2120 if (Pointee->isArrayType() && !ArrayForm) {
2121 Diag(StartLoc, diag::warn_delete_array_type)
2122 << Type << Ex.get()->getSourceRange()
2123 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2127 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2128 ArrayForm ? OO_Array_Delete : OO_Delete);
2132 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2136 // If we're allocating an array of records, check whether the
2137 // usual operator delete[] has a size_t parameter.
2139 // If the user specifically asked to use the global allocator,
2140 // we'll need to do the lookup into the class.
2142 UsualArrayDeleteWantsSize =
2143 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2145 // Otherwise, the usual operator delete[] should be the
2146 // function we just found.
2147 else if (isa<CXXMethodDecl>(OperatorDelete))
2148 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2151 if (!PointeeRD->hasIrrelevantDestructor())
2152 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2153 MarkFunctionReferenced(StartLoc,
2154 const_cast<CXXDestructorDecl*>(Dtor));
2155 DiagnoseUseOfDecl(Dtor, StartLoc);
2158 // C++ [expr.delete]p3:
2159 // In the first alternative (delete object), if the static type of the
2160 // object to be deleted is different from its dynamic type, the static
2161 // type shall be a base class of the dynamic type of the object to be
2162 // deleted and the static type shall have a virtual destructor or the
2163 // behavior is undefined.
2165 // Note: a final class cannot be derived from, no issue there
2166 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
2167 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
2168 if (dtor && !dtor->isVirtual()) {
2169 if (PointeeRD->isAbstract()) {
2170 // If the class is abstract, we warn by default, because we're
2171 // sure the code has undefined behavior.
2172 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2174 } else if (!ArrayForm) {
2175 // Otherwise, if this is not an array delete, it's a bit suspect,
2176 // but not necessarily wrong.
2177 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2184 if (!OperatorDelete) {
2185 // Look for a global declaration.
2186 DeclareGlobalNewDelete();
2187 DeclContext *TUDecl = Context.getTranslationUnitDecl();
2188 Expr *Arg = Ex.get();
2189 if (!Context.hasSameType(Arg->getType(), Context.VoidPtrTy))
2190 Arg = ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
2191 CK_BitCast, Arg, 0, VK_RValue);
2192 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
2193 &Arg, 1, TUDecl, /*AllowMissing=*/false,
2198 MarkFunctionReferenced(StartLoc, OperatorDelete);
2200 // Check access and ambiguity of operator delete and destructor.
2202 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2203 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
2204 PDiag(diag::err_access_dtor) << PointeeElem);
2210 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
2212 UsualArrayDeleteWantsSize,
2213 OperatorDelete, Ex.take(), StartLoc));
2216 /// \brief Check the use of the given variable as a C++ condition in an if,
2217 /// while, do-while, or switch statement.
2218 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
2219 SourceLocation StmtLoc,
2220 bool ConvertToBoolean) {
2221 QualType T = ConditionVar->getType();
2223 // C++ [stmt.select]p2:
2224 // The declarator shall not specify a function or an array.
2225 if (T->isFunctionType())
2226 return ExprError(Diag(ConditionVar->getLocation(),
2227 diag::err_invalid_use_of_function_type)
2228 << ConditionVar->getSourceRange());
2229 else if (T->isArrayType())
2230 return ExprError(Diag(ConditionVar->getLocation(),
2231 diag::err_invalid_use_of_array_type)
2232 << ConditionVar->getSourceRange());
2234 ExprResult Condition =
2235 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2238 /*enclosing*/ false,
2239 ConditionVar->getLocation(),
2240 ConditionVar->getType().getNonReferenceType(),
2243 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
2245 if (ConvertToBoolean) {
2246 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2247 if (Condition.isInvalid())
2254 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
2255 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
2257 // The value of a condition that is an initialized declaration in a statement
2258 // other than a switch statement is the value of the declared variable
2259 // implicitly converted to type bool. If that conversion is ill-formed, the
2260 // program is ill-formed.
2261 // The value of a condition that is an expression is the value of the
2262 // expression, implicitly converted to bool.
2264 return PerformContextuallyConvertToBool(CondExpr);
2267 /// Helper function to determine whether this is the (deprecated) C++
2268 /// conversion from a string literal to a pointer to non-const char or
2269 /// non-const wchar_t (for narrow and wide string literals,
2272 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2273 // Look inside the implicit cast, if it exists.
2274 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2275 From = Cast->getSubExpr();
2277 // A string literal (2.13.4) that is not a wide string literal can
2278 // be converted to an rvalue of type "pointer to char"; a wide
2279 // string literal can be converted to an rvalue of type "pointer
2280 // to wchar_t" (C++ 4.2p2).
2281 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
2282 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
2283 if (const BuiltinType *ToPointeeType
2284 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
2285 // This conversion is considered only when there is an
2286 // explicit appropriate pointer target type (C++ 4.2p2).
2287 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2288 switch (StrLit->getKind()) {
2289 case StringLiteral::UTF8:
2290 case StringLiteral::UTF16:
2291 case StringLiteral::UTF32:
2292 // We don't allow UTF literals to be implicitly converted
2294 case StringLiteral::Ascii:
2295 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2296 ToPointeeType->getKind() == BuiltinType::Char_S);
2297 case StringLiteral::Wide:
2298 return ToPointeeType->isWideCharType();
2306 static ExprResult BuildCXXCastArgument(Sema &S,
2307 SourceLocation CastLoc,
2310 CXXMethodDecl *Method,
2311 DeclAccessPair FoundDecl,
2312 bool HadMultipleCandidates,
2315 default: llvm_unreachable("Unhandled cast kind!");
2316 case CK_ConstructorConversion: {
2317 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
2318 SmallVector<Expr*, 8> ConstructorArgs;
2320 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
2323 S.CheckConstructorAccess(CastLoc, Constructor,
2324 InitializedEntity::InitializeTemporary(Ty),
2325 Constructor->getAccess());
2328 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2330 HadMultipleCandidates, /*ZeroInit*/ false,
2331 CXXConstructExpr::CK_Complete, SourceRange());
2332 if (Result.isInvalid())
2335 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2338 case CK_UserDefinedConversion: {
2339 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2341 // Create an implicit call expr that calls it.
2342 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2343 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
2344 HadMultipleCandidates);
2345 if (Result.isInvalid())
2347 // Record usage of conversion in an implicit cast.
2348 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2349 Result.get()->getType(),
2350 CK_UserDefinedConversion,
2352 Result.get()->getValueKind()));
2354 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2356 return S.MaybeBindToTemporary(Result.get());
2361 /// PerformImplicitConversion - Perform an implicit conversion of the
2362 /// expression From to the type ToType using the pre-computed implicit
2363 /// conversion sequence ICS. Returns the converted
2364 /// expression. Action is the kind of conversion we're performing,
2365 /// used in the error message.
2367 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2368 const ImplicitConversionSequence &ICS,
2369 AssignmentAction Action,
2370 CheckedConversionKind CCK) {
2371 switch (ICS.getKind()) {
2372 case ImplicitConversionSequence::StandardConversion: {
2373 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2375 if (Res.isInvalid())
2381 case ImplicitConversionSequence::UserDefinedConversion: {
2383 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
2385 QualType BeforeToType;
2386 assert(FD && "FIXME: aggregate initialization from init list");
2387 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
2388 CastKind = CK_UserDefinedConversion;
2390 // If the user-defined conversion is specified by a conversion function,
2391 // the initial standard conversion sequence converts the source type to
2392 // the implicit object parameter of the conversion function.
2393 BeforeToType = Context.getTagDeclType(Conv->getParent());
2395 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
2396 CastKind = CK_ConstructorConversion;
2397 // Do no conversion if dealing with ... for the first conversion.
2398 if (!ICS.UserDefined.EllipsisConversion) {
2399 // If the user-defined conversion is specified by a constructor, the
2400 // initial standard conversion sequence converts the source type to the
2401 // type required by the argument of the constructor
2402 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2405 // Watch out for elipsis conversion.
2406 if (!ICS.UserDefined.EllipsisConversion) {
2408 PerformImplicitConversion(From, BeforeToType,
2409 ICS.UserDefined.Before, AA_Converting,
2411 if (Res.isInvalid())
2417 = BuildCXXCastArgument(*this,
2418 From->getLocStart(),
2419 ToType.getNonReferenceType(),
2420 CastKind, cast<CXXMethodDecl>(FD),
2421 ICS.UserDefined.FoundConversionFunction,
2422 ICS.UserDefined.HadMultipleCandidates,
2425 if (CastArg.isInvalid())
2428 From = CastArg.take();
2430 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2431 AA_Converting, CCK);
2434 case ImplicitConversionSequence::AmbiguousConversion:
2435 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2436 PDiag(diag::err_typecheck_ambiguous_condition)
2437 << From->getSourceRange());
2440 case ImplicitConversionSequence::EllipsisConversion:
2441 llvm_unreachable("Cannot perform an ellipsis conversion");
2443 case ImplicitConversionSequence::BadConversion:
2447 // Everything went well.
2451 /// PerformImplicitConversion - Perform an implicit conversion of the
2452 /// expression From to the type ToType by following the standard
2453 /// conversion sequence SCS. Returns the converted
2454 /// expression. Flavor is the context in which we're performing this
2455 /// conversion, for use in error messages.
2457 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2458 const StandardConversionSequence& SCS,
2459 AssignmentAction Action,
2460 CheckedConversionKind CCK) {
2461 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2463 // Overall FIXME: we are recomputing too many types here and doing far too
2464 // much extra work. What this means is that we need to keep track of more
2465 // information that is computed when we try the implicit conversion initially,
2466 // so that we don't need to recompute anything here.
2467 QualType FromType = From->getType();
2469 if (SCS.CopyConstructor) {
2470 // FIXME: When can ToType be a reference type?
2471 assert(!ToType->isReferenceType());
2472 if (SCS.Second == ICK_Derived_To_Base) {
2473 SmallVector<Expr*, 8> ConstructorArgs;
2474 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2475 From, /*FIXME:ConstructLoc*/SourceLocation(),
2478 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2479 ToType, SCS.CopyConstructor,
2481 /*HadMultipleCandidates*/ false,
2483 CXXConstructExpr::CK_Complete,
2486 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2487 ToType, SCS.CopyConstructor,
2488 From, /*HadMultipleCandidates*/ false,
2490 CXXConstructExpr::CK_Complete,
2494 // Resolve overloaded function references.
2495 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2496 DeclAccessPair Found;
2497 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2502 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
2505 From = FixOverloadedFunctionReference(From, Found, Fn);
2506 FromType = From->getType();
2509 // Perform the first implicit conversion.
2510 switch (SCS.First) {
2515 case ICK_Lvalue_To_Rvalue: {
2516 assert(From->getObjectKind() != OK_ObjCProperty);
2517 FromType = FromType.getUnqualifiedType();
2518 ExprResult FromRes = DefaultLvalueConversion(From);
2519 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2520 From = FromRes.take();
2524 case ICK_Array_To_Pointer:
2525 FromType = Context.getArrayDecayedType(FromType);
2526 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2527 VK_RValue, /*BasePath=*/0, CCK).take();
2530 case ICK_Function_To_Pointer:
2531 FromType = Context.getPointerType(FromType);
2532 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2533 VK_RValue, /*BasePath=*/0, CCK).take();
2537 llvm_unreachable("Improper first standard conversion");
2540 // Perform the second implicit conversion
2541 switch (SCS.Second) {
2543 // If both sides are functions (or pointers/references to them), there could
2544 // be incompatible exception declarations.
2545 if (CheckExceptionSpecCompatibility(From, ToType))
2547 // Nothing else to do.
2550 case ICK_NoReturn_Adjustment:
2551 // If both sides are functions (or pointers/references to them), there could
2552 // be incompatible exception declarations.
2553 if (CheckExceptionSpecCompatibility(From, ToType))
2556 From = ImpCastExprToType(From, ToType, CK_NoOp,
2557 VK_RValue, /*BasePath=*/0, CCK).take();
2560 case ICK_Integral_Promotion:
2561 case ICK_Integral_Conversion:
2562 if (ToType->isBooleanType()) {
2563 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
2564 SCS.Second == ICK_Integral_Promotion &&
2565 "only enums with fixed underlying type can promote to bool");
2566 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
2567 VK_RValue, /*BasePath=*/0, CCK).take();
2569 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2570 VK_RValue, /*BasePath=*/0, CCK).take();
2574 case ICK_Floating_Promotion:
2575 case ICK_Floating_Conversion:
2576 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2577 VK_RValue, /*BasePath=*/0, CCK).take();
2580 case ICK_Complex_Promotion:
2581 case ICK_Complex_Conversion: {
2582 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2583 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2585 if (FromEl->isRealFloatingType()) {
2586 if (ToEl->isRealFloatingType())
2587 CK = CK_FloatingComplexCast;
2589 CK = CK_FloatingComplexToIntegralComplex;
2590 } else if (ToEl->isRealFloatingType()) {
2591 CK = CK_IntegralComplexToFloatingComplex;
2593 CK = CK_IntegralComplexCast;
2595 From = ImpCastExprToType(From, ToType, CK,
2596 VK_RValue, /*BasePath=*/0, CCK).take();
2600 case ICK_Floating_Integral:
2601 if (ToType->isRealFloatingType())
2602 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2603 VK_RValue, /*BasePath=*/0, CCK).take();
2605 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2606 VK_RValue, /*BasePath=*/0, CCK).take();
2609 case ICK_Compatible_Conversion:
2610 From = ImpCastExprToType(From, ToType, CK_NoOp,
2611 VK_RValue, /*BasePath=*/0, CCK).take();
2614 case ICK_Writeback_Conversion:
2615 case ICK_Pointer_Conversion: {
2616 if (SCS.IncompatibleObjC && Action != AA_Casting) {
2617 // Diagnose incompatible Objective-C conversions
2618 if (Action == AA_Initializing || Action == AA_Assigning)
2619 Diag(From->getLocStart(),
2620 diag::ext_typecheck_convert_incompatible_pointer)
2621 << ToType << From->getType() << Action
2622 << From->getSourceRange() << 0;
2624 Diag(From->getLocStart(),
2625 diag::ext_typecheck_convert_incompatible_pointer)
2626 << From->getType() << ToType << Action
2627 << From->getSourceRange() << 0;
2629 if (From->getType()->isObjCObjectPointerType() &&
2630 ToType->isObjCObjectPointerType())
2631 EmitRelatedResultTypeNote(From);
2633 else if (getLangOpts().ObjCAutoRefCount &&
2634 !CheckObjCARCUnavailableWeakConversion(ToType,
2636 if (Action == AA_Initializing)
2637 Diag(From->getLocStart(),
2638 diag::err_arc_weak_unavailable_assign);
2640 Diag(From->getLocStart(),
2641 diag::err_arc_convesion_of_weak_unavailable)
2642 << (Action == AA_Casting) << From->getType() << ToType
2643 << From->getSourceRange();
2646 CastKind Kind = CK_Invalid;
2647 CXXCastPath BasePath;
2648 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2651 // Make sure we extend blocks if necessary.
2652 // FIXME: doing this here is really ugly.
2653 if (Kind == CK_BlockPointerToObjCPointerCast) {
2654 ExprResult E = From;
2655 (void) PrepareCastToObjCObjectPointer(E);
2659 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2664 case ICK_Pointer_Member: {
2665 CastKind Kind = CK_Invalid;
2666 CXXCastPath BasePath;
2667 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2669 if (CheckExceptionSpecCompatibility(From, ToType))
2671 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2676 case ICK_Boolean_Conversion:
2677 // Perform half-to-boolean conversion via float.
2678 if (From->getType()->isHalfType()) {
2679 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2680 FromType = Context.FloatTy;
2683 From = ImpCastExprToType(From, Context.BoolTy,
2684 ScalarTypeToBooleanCastKind(FromType),
2685 VK_RValue, /*BasePath=*/0, CCK).take();
2688 case ICK_Derived_To_Base: {
2689 CXXCastPath BasePath;
2690 if (CheckDerivedToBaseConversion(From->getType(),
2691 ToType.getNonReferenceType(),
2692 From->getLocStart(),
2693 From->getSourceRange(),
2698 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2699 CK_DerivedToBase, From->getValueKind(),
2700 &BasePath, CCK).take();
2704 case ICK_Vector_Conversion:
2705 From = ImpCastExprToType(From, ToType, CK_BitCast,
2706 VK_RValue, /*BasePath=*/0, CCK).take();
2709 case ICK_Vector_Splat:
2710 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2711 VK_RValue, /*BasePath=*/0, CCK).take();
2714 case ICK_Complex_Real:
2715 // Case 1. x -> _Complex y
2716 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2717 QualType ElType = ToComplex->getElementType();
2718 bool isFloatingComplex = ElType->isRealFloatingType();
2721 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2723 } else if (From->getType()->isRealFloatingType()) {
2724 From = ImpCastExprToType(From, ElType,
2725 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
2727 assert(From->getType()->isIntegerType());
2728 From = ImpCastExprToType(From, ElType,
2729 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
2732 From = ImpCastExprToType(From, ToType,
2733 isFloatingComplex ? CK_FloatingRealToComplex
2734 : CK_IntegralRealToComplex).take();
2736 // Case 2. _Complex x -> y
2738 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2739 assert(FromComplex);
2741 QualType ElType = FromComplex->getElementType();
2742 bool isFloatingComplex = ElType->isRealFloatingType();
2745 From = ImpCastExprToType(From, ElType,
2746 isFloatingComplex ? CK_FloatingComplexToReal
2747 : CK_IntegralComplexToReal,
2748 VK_RValue, /*BasePath=*/0, CCK).take();
2751 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2753 } else if (ToType->isRealFloatingType()) {
2754 From = ImpCastExprToType(From, ToType,
2755 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2756 VK_RValue, /*BasePath=*/0, CCK).take();
2758 assert(ToType->isIntegerType());
2759 From = ImpCastExprToType(From, ToType,
2760 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2761 VK_RValue, /*BasePath=*/0, CCK).take();
2766 case ICK_Block_Pointer_Conversion: {
2767 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2768 VK_RValue, /*BasePath=*/0, CCK).take();
2772 case ICK_TransparentUnionConversion: {
2773 ExprResult FromRes = Owned(From);
2774 Sema::AssignConvertType ConvTy =
2775 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2776 if (FromRes.isInvalid())
2778 From = FromRes.take();
2779 assert ((ConvTy == Sema::Compatible) &&
2780 "Improper transparent union conversion");
2785 case ICK_Lvalue_To_Rvalue:
2786 case ICK_Array_To_Pointer:
2787 case ICK_Function_To_Pointer:
2788 case ICK_Qualification:
2789 case ICK_Num_Conversion_Kinds:
2790 llvm_unreachable("Improper second standard conversion");
2793 switch (SCS.Third) {
2798 case ICK_Qualification: {
2799 // The qualification keeps the category of the inner expression, unless the
2800 // target type isn't a reference.
2801 ExprValueKind VK = ToType->isReferenceType() ?
2802 From->getValueKind() : VK_RValue;
2803 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2804 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
2806 if (SCS.DeprecatedStringLiteralToCharPtr &&
2807 !getLangOpts().WritableStrings)
2808 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2809 << ToType.getNonReferenceType();
2815 llvm_unreachable("Improper third standard conversion");
2818 // If this conversion sequence involved a scalar -> atomic conversion, perform
2819 // that conversion now.
2820 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>())
2821 if (Context.hasSameType(ToAtomic->getValueType(), From->getType()))
2822 From = ImpCastExprToType(From, ToType, CK_NonAtomicToAtomic, VK_RValue, 0,
2828 ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
2829 SourceLocation KWLoc,
2831 SourceLocation RParen) {
2832 TypeSourceInfo *TSInfo;
2833 QualType T = GetTypeFromParser(Ty, &TSInfo);
2836 TSInfo = Context.getTrivialTypeSourceInfo(T);
2837 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
2840 /// \brief Check the completeness of a type in a unary type trait.
2842 /// If the particular type trait requires a complete type, tries to complete
2843 /// it. If completing the type fails, a diagnostic is emitted and false
2844 /// returned. If completing the type succeeds or no completion was required,
2846 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2850 // C++0x [meta.unary.prop]p3:
2851 // For all of the class templates X declared in this Clause, instantiating
2852 // that template with a template argument that is a class template
2853 // specialization may result in the implicit instantiation of the template
2854 // argument if and only if the semantics of X require that the argument
2855 // must be a complete type.
2856 // We apply this rule to all the type trait expressions used to implement
2857 // these class templates. We also try to follow any GCC documented behavior
2858 // in these expressions to ensure portability of standard libraries.
2860 // is_complete_type somewhat obviously cannot require a complete type.
2861 case UTT_IsCompleteType:
2864 // These traits are modeled on the type predicates in C++0x
2865 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2866 // requiring a complete type, as whether or not they return true cannot be
2867 // impacted by the completeness of the type.
2869 case UTT_IsIntegral:
2870 case UTT_IsFloatingPoint:
2873 case UTT_IsLvalueReference:
2874 case UTT_IsRvalueReference:
2875 case UTT_IsMemberFunctionPointer:
2876 case UTT_IsMemberObjectPointer:
2880 case UTT_IsFunction:
2881 case UTT_IsReference:
2882 case UTT_IsArithmetic:
2883 case UTT_IsFundamental:
2886 case UTT_IsCompound:
2887 case UTT_IsMemberPointer:
2890 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2891 // which requires some of its traits to have the complete type. However,
2892 // the completeness of the type cannot impact these traits' semantics, and
2893 // so they don't require it. This matches the comments on these traits in
2896 case UTT_IsVolatile:
2898 case UTT_IsUnsigned:
2901 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
2902 // applied to a complete type.
2904 case UTT_IsTriviallyCopyable:
2905 case UTT_IsStandardLayout:
2909 case UTT_IsPolymorphic:
2910 case UTT_IsAbstract:
2911 case UTT_IsInterfaceClass:
2914 // These traits require a complete type.
2917 // These trait expressions are designed to help implement predicates in
2918 // [meta.unary.prop] despite not being named the same. They are specified
2919 // by both GCC and the Embarcadero C++ compiler, and require the complete
2920 // type due to the overarching C++0x type predicates being implemented
2921 // requiring the complete type.
2922 case UTT_HasNothrowAssign:
2923 case UTT_HasNothrowConstructor:
2924 case UTT_HasNothrowCopy:
2925 case UTT_HasTrivialAssign:
2926 case UTT_HasTrivialDefaultConstructor:
2927 case UTT_HasTrivialCopy:
2928 case UTT_HasTrivialDestructor:
2929 case UTT_HasVirtualDestructor:
2930 // Arrays of unknown bound are expressly allowed.
2931 QualType ElTy = ArgTy;
2932 if (ArgTy->isIncompleteArrayType())
2933 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2935 // The void type is expressly allowed.
2936 if (ElTy->isVoidType())
2939 return !S.RequireCompleteType(
2940 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
2942 llvm_unreachable("Type trait not handled by switch");
2945 static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2946 SourceLocation KeyLoc, QualType T) {
2947 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
2949 ASTContext &C = Self.Context;
2951 // Type trait expressions corresponding to the primary type category
2952 // predicates in C++0x [meta.unary.cat].
2954 return T->isVoidType();
2955 case UTT_IsIntegral:
2956 return T->isIntegralType(C);
2957 case UTT_IsFloatingPoint:
2958 return T->isFloatingType();
2960 return T->isArrayType();
2962 return T->isPointerType();
2963 case UTT_IsLvalueReference:
2964 return T->isLValueReferenceType();
2965 case UTT_IsRvalueReference:
2966 return T->isRValueReferenceType();
2967 case UTT_IsMemberFunctionPointer:
2968 return T->isMemberFunctionPointerType();
2969 case UTT_IsMemberObjectPointer:
2970 return T->isMemberDataPointerType();
2972 return T->isEnumeralType();
2974 return T->isUnionType();
2976 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
2977 case UTT_IsFunction:
2978 return T->isFunctionType();
2980 // Type trait expressions which correspond to the convenient composition
2981 // predicates in C++0x [meta.unary.comp].
2982 case UTT_IsReference:
2983 return T->isReferenceType();
2984 case UTT_IsArithmetic:
2985 return T->isArithmeticType() && !T->isEnumeralType();
2986 case UTT_IsFundamental:
2987 return T->isFundamentalType();
2989 return T->isObjectType();
2991 // Note: semantic analysis depends on Objective-C lifetime types to be
2992 // considered scalar types. However, such types do not actually behave
2993 // like scalar types at run time (since they may require retain/release
2994 // operations), so we report them as non-scalar.
2995 if (T->isObjCLifetimeType()) {
2996 switch (T.getObjCLifetime()) {
2997 case Qualifiers::OCL_None:
2998 case Qualifiers::OCL_ExplicitNone:
3001 case Qualifiers::OCL_Strong:
3002 case Qualifiers::OCL_Weak:
3003 case Qualifiers::OCL_Autoreleasing:
3008 return T->isScalarType();
3009 case UTT_IsCompound:
3010 return T->isCompoundType();
3011 case UTT_IsMemberPointer:
3012 return T->isMemberPointerType();
3014 // Type trait expressions which correspond to the type property predicates
3015 // in C++0x [meta.unary.prop].
3017 return T.isConstQualified();
3018 case UTT_IsVolatile:
3019 return T.isVolatileQualified();
3021 return T.isTrivialType(Self.Context);
3022 case UTT_IsTriviallyCopyable:
3023 return T.isTriviallyCopyableType(Self.Context);
3024 case UTT_IsStandardLayout:
3025 return T->isStandardLayoutType();
3027 return T.isPODType(Self.Context);
3029 return T->isLiteralType();
3031 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3032 return !RD->isUnion() && RD->isEmpty();
3034 case UTT_IsPolymorphic:
3035 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3036 return RD->isPolymorphic();
3038 case UTT_IsAbstract:
3039 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3040 return RD->isAbstract();
3042 case UTT_IsInterfaceClass:
3043 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3044 return RD->isInterface();
3047 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3048 return RD->hasAttr<FinalAttr>();
3051 return T->isSignedIntegerType();
3052 case UTT_IsUnsigned:
3053 return T->isUnsignedIntegerType();
3055 // Type trait expressions which query classes regarding their construction,
3056 // destruction, and copying. Rather than being based directly on the
3057 // related type predicates in the standard, they are specified by both
3058 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3061 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3062 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3063 case UTT_HasTrivialDefaultConstructor:
3064 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3065 // If __is_pod (type) is true then the trait is true, else if type is
3066 // a cv class or union type (or array thereof) with a trivial default
3067 // constructor ([class.ctor]) then the trait is true, else it is false.
3068 if (T.isPODType(Self.Context))
3070 if (const RecordType *RT =
3071 C.getBaseElementType(T)->getAs<RecordType>())
3072 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
3074 case UTT_HasTrivialCopy:
3075 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3076 // If __is_pod (type) is true or type is a reference type then
3077 // the trait is true, else if type is a cv class or union type
3078 // with a trivial copy constructor ([class.copy]) then the trait
3079 // is true, else it is false.
3080 if (T.isPODType(Self.Context) || T->isReferenceType())
3082 if (const RecordType *RT = T->getAs<RecordType>())
3083 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
3085 case UTT_HasTrivialAssign:
3086 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3087 // If type is const qualified or is a reference type then the
3088 // trait is false. Otherwise if __is_pod (type) is true then the
3089 // trait is true, else if type is a cv class or union type with
3090 // a trivial copy assignment ([class.copy]) then the trait is
3091 // true, else it is false.
3092 // Note: the const and reference restrictions are interesting,
3093 // given that const and reference members don't prevent a class
3094 // from having a trivial copy assignment operator (but do cause
3095 // errors if the copy assignment operator is actually used, q.v.
3096 // [class.copy]p12).
3098 if (C.getBaseElementType(T).isConstQualified())
3100 if (T.isPODType(Self.Context))
3102 if (const RecordType *RT = T->getAs<RecordType>())
3103 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
3105 case UTT_HasTrivialDestructor:
3106 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3107 // If __is_pod (type) is true or type is a reference type
3108 // then the trait is true, else if type is a cv class or union
3109 // type (or array thereof) with a trivial destructor
3110 // ([class.dtor]) then the trait is true, else it is
3112 if (T.isPODType(Self.Context) || T->isReferenceType())
3115 // Objective-C++ ARC: autorelease types don't require destruction.
3116 if (T->isObjCLifetimeType() &&
3117 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3120 if (const RecordType *RT =
3121 C.getBaseElementType(T)->getAs<RecordType>())
3122 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
3124 // TODO: Propagate nothrowness for implicitly declared special members.
3125 case UTT_HasNothrowAssign:
3126 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3127 // If type is const qualified or is a reference type then the
3128 // trait is false. Otherwise if __has_trivial_assign (type)
3129 // is true then the trait is true, else if type is a cv class
3130 // or union type with copy assignment operators that are known
3131 // not to throw an exception then the trait is true, else it is
3133 if (C.getBaseElementType(T).isConstQualified())
3135 if (T->isReferenceType())
3137 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3139 if (const RecordType *RT = T->getAs<RecordType>()) {
3140 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
3141 if (RD->hasTrivialCopyAssignment())
3144 bool FoundAssign = false;
3145 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
3146 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
3147 Sema::LookupOrdinaryName);
3148 if (Self.LookupQualifiedName(Res, RD)) {
3149 Res.suppressDiagnostics();
3150 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3151 Op != OpEnd; ++Op) {
3152 if (isa<FunctionTemplateDecl>(*Op))
3155 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3156 if (Operator->isCopyAssignmentOperator()) {
3158 const FunctionProtoType *CPT
3159 = Operator->getType()->getAs<FunctionProtoType>();
3160 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3163 if (!CPT->isNothrow(Self.Context))
3172 case UTT_HasNothrowCopy:
3173 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3174 // If __has_trivial_copy (type) is true then the trait is true, else
3175 // if type is a cv class or union type with copy constructors that are
3176 // known not to throw an exception then the trait is true, else it is
3178 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
3180 if (const RecordType *RT = T->getAs<RecordType>()) {
3181 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3182 if (RD->hasTrivialCopyConstructor())
3185 bool FoundConstructor = false;
3187 DeclContext::lookup_const_iterator Con, ConEnd;
3188 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3189 Con != ConEnd; ++Con) {
3190 // A template constructor is never a copy constructor.
3191 // FIXME: However, it may actually be selected at the actual overload
3192 // resolution point.
3193 if (isa<FunctionTemplateDecl>(*Con))
3195 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3196 if (Constructor->isCopyConstructor(FoundTQs)) {
3197 FoundConstructor = true;
3198 const FunctionProtoType *CPT
3199 = Constructor->getType()->getAs<FunctionProtoType>();
3200 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3203 // FIXME: check whether evaluating default arguments can throw.
3204 // For now, we'll be conservative and assume that they can throw.
3205 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3210 return FoundConstructor;
3213 case UTT_HasNothrowConstructor:
3214 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3215 // If __has_trivial_constructor (type) is true then the trait is
3216 // true, else if type is a cv class or union type (or array
3217 // thereof) with a default constructor that is known not to
3218 // throw an exception then the trait is true, else it is false.
3219 if (T.isPODType(C) || T->isObjCLifetimeType())
3221 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3222 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3223 if (RD->hasTrivialDefaultConstructor())
3226 DeclContext::lookup_const_iterator Con, ConEnd;
3227 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3228 Con != ConEnd; ++Con) {
3229 // FIXME: In C++0x, a constructor template can be a default constructor.
3230 if (isa<FunctionTemplateDecl>(*Con))
3232 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3233 if (Constructor->isDefaultConstructor()) {
3234 const FunctionProtoType *CPT
3235 = Constructor->getType()->getAs<FunctionProtoType>();
3236 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3239 // TODO: check whether evaluating default arguments can throw.
3240 // For now, we'll be conservative and assume that they can throw.
3241 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
3246 case UTT_HasVirtualDestructor:
3247 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3248 // If type is a class type with a virtual destructor ([class.dtor])
3249 // then the trait is true, else it is false.
3250 if (const RecordType *Record = T->getAs<RecordType>()) {
3251 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3252 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
3253 return Destructor->isVirtual();
3257 // These type trait expressions are modeled on the specifications for the
3258 // Embarcadero C++0x type trait functions:
3259 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3260 case UTT_IsCompleteType:
3261 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3262 // Returns True if and only if T is a complete type at the point of the
3264 return !T->isIncompleteType();
3266 llvm_unreachable("Type trait not covered by switch");
3269 ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
3270 SourceLocation KWLoc,
3271 TypeSourceInfo *TSInfo,
3272 SourceLocation RParen) {
3273 QualType T = TSInfo->getType();
3274 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3278 if (!T->isDependentType())
3279 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
3281 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
3282 RParen, Context.BoolTy));
3285 ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3286 SourceLocation KWLoc,
3289 SourceLocation RParen) {
3290 TypeSourceInfo *LhsTSInfo;
3291 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3293 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3295 TypeSourceInfo *RhsTSInfo;
3296 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3298 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3300 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3303 /// \brief Determine whether T has a non-trivial Objective-C lifetime in
3305 static bool hasNontrivialObjCLifetime(QualType T) {
3306 switch (T.getObjCLifetime()) {
3307 case Qualifiers::OCL_ExplicitNone:
3310 case Qualifiers::OCL_Strong:
3311 case Qualifiers::OCL_Weak:
3312 case Qualifiers::OCL_Autoreleasing:
3315 case Qualifiers::OCL_None:
3316 return T->isObjCLifetimeType();
3319 llvm_unreachable("Unknown ObjC lifetime qualifier");
3322 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3323 ArrayRef<TypeSourceInfo *> Args,
3324 SourceLocation RParenLoc) {
3326 case clang::TT_IsTriviallyConstructible: {
3327 // C++11 [meta.unary.prop]:
3328 // is_trivially_constructible is defined as:
3330 // is_constructible<T, Args...>::value is true and the variable
3331 // definition for is_constructible, as defined below, is known to call no
3332 // operation that is not trivial.
3334 // The predicate condition for a template specialization
3335 // is_constructible<T, Args...> shall be satisfied if and only if the
3336 // following variable definition would be well-formed for some invented
3339 // T t(create<Args>()...);
3341 S.Diag(KWLoc, diag::err_type_trait_arity)
3342 << 1 << 1 << 1 << (int)Args.size();
3346 bool SawVoid = false;
3347 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3348 if (Args[I]->getType()->isVoidType()) {
3353 if (!Args[I]->getType()->isIncompleteType() &&
3354 S.RequireCompleteType(KWLoc, Args[I]->getType(),
3355 diag::err_incomplete_type_used_in_type_trait_expr))
3359 // If any argument was 'void', of course it won't type-check.
3363 llvm::SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3364 llvm::SmallVector<Expr *, 2> ArgExprs;
3365 ArgExprs.reserve(Args.size() - 1);
3366 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3367 QualType T = Args[I]->getType();
3368 if (T->isObjectType() || T->isFunctionType())
3369 T = S.Context.getRValueReferenceType(T);
3370 OpaqueArgExprs.push_back(
3371 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
3372 T.getNonLValueExprType(S.Context),
3373 Expr::getValueKindForType(T)));
3374 ArgExprs.push_back(&OpaqueArgExprs.back());
3377 // Perform the initialization in an unevaluated context within a SFINAE
3378 // trap at translation unit scope.
3379 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3380 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3381 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3382 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3383 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3385 InitializationSequence Init(S, To, InitKind,
3386 ArgExprs.begin(), ArgExprs.size());
3390 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
3391 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3394 // Under Objective-C ARC, if the destination has non-trivial Objective-C
3395 // lifetime, this is a non-trivial construction.
3396 if (S.getLangOpts().ObjCAutoRefCount &&
3397 hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType()))
3400 // The initialization succeeded; now make sure there are no non-trivial
3402 return !Result.get()->hasNonTrivialCall(S.Context);
3409 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3410 ArrayRef<TypeSourceInfo *> Args,
3411 SourceLocation RParenLoc) {
3412 bool Dependent = false;
3413 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3414 if (Args[I]->getType()->isDependentType()) {
3422 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3424 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3425 Args, RParenLoc, Value);
3428 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3429 ArrayRef<ParsedType> Args,
3430 SourceLocation RParenLoc) {
3431 llvm::SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3432 ConvertedArgs.reserve(Args.size());
3434 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3435 TypeSourceInfo *TInfo;
3436 QualType T = GetTypeFromParser(Args[I], &TInfo);
3438 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3440 ConvertedArgs.push_back(TInfo);
3443 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3446 static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3447 QualType LhsT, QualType RhsT,
3448 SourceLocation KeyLoc) {
3449 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3450 "Cannot evaluate traits of dependent types");
3453 case BTT_IsBaseOf: {
3454 // C++0x [meta.rel]p2
3455 // Base is a base class of Derived without regard to cv-qualifiers or
3456 // Base and Derived are not unions and name the same class type without
3457 // regard to cv-qualifiers.
3459 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3460 if (!lhsRecord) return false;
3462 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3463 if (!rhsRecord) return false;
3465 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3466 == (lhsRecord == rhsRecord));
3468 if (lhsRecord == rhsRecord)
3469 return !lhsRecord->getDecl()->isUnion();
3471 // C++0x [meta.rel]p2:
3472 // If Base and Derived are class types and are different types
3473 // (ignoring possible cv-qualifiers) then Derived shall be a
3475 if (Self.RequireCompleteType(KeyLoc, RhsT,
3476 diag::err_incomplete_type_used_in_type_trait_expr))
3479 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3480 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3483 return Self.Context.hasSameType(LhsT, RhsT);
3484 case BTT_TypeCompatible:
3485 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3486 RhsT.getUnqualifiedType());
3487 case BTT_IsConvertible:
3488 case BTT_IsConvertibleTo: {
3489 // C++0x [meta.rel]p4:
3490 // Given the following function prototype:
3492 // template <class T>
3493 // typename add_rvalue_reference<T>::type create();
3495 // the predicate condition for a template specialization
3496 // is_convertible<From, To> shall be satisfied if and only if
3497 // the return expression in the following code would be
3498 // well-formed, including any implicit conversions to the return
3499 // type of the function:
3502 // return create<From>();
3505 // Access checking is performed as if in a context unrelated to To and
3506 // From. Only the validity of the immediate context of the expression
3507 // of the return-statement (including conversions to the return type)
3510 // We model the initialization as a copy-initialization of a temporary
3511 // of the appropriate type, which for this expression is identical to the
3512 // return statement (since NRVO doesn't apply).
3514 // Functions aren't allowed to return function or array types.
3515 if (RhsT->isFunctionType() || RhsT->isArrayType())
3518 // A return statement in a void function must have void type.
3519 if (RhsT->isVoidType())
3520 return LhsT->isVoidType();
3522 // A function definition requires a complete, non-abstract return type.
3523 if (Self.RequireCompleteType(KeyLoc, RhsT, 0) ||
3524 Self.RequireNonAbstractType(KeyLoc, RhsT, 0))
3527 // Compute the result of add_rvalue_reference.
3528 if (LhsT->isObjectType() || LhsT->isFunctionType())
3529 LhsT = Self.Context.getRValueReferenceType(LhsT);
3531 // Build a fake source and destination for initialization.
3532 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
3533 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3534 Expr::getValueKindForType(LhsT));
3535 Expr *FromPtr = &From;
3536 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3539 // Perform the initialization in an unevaluated context within a SFINAE
3540 // trap at translation unit scope.
3541 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3542 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3543 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3544 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
3548 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
3549 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3552 case BTT_IsTriviallyAssignable: {
3553 // C++11 [meta.unary.prop]p3:
3554 // is_trivially_assignable is defined as:
3555 // is_assignable<T, U>::value is true and the assignment, as defined by
3556 // is_assignable, is known to call no operation that is not trivial
3558 // is_assignable is defined as:
3559 // The expression declval<T>() = declval<U>() is well-formed when
3560 // treated as an unevaluated operand (Clause 5).
3562 // For both, T and U shall be complete types, (possibly cv-qualified)
3563 // void, or arrays of unknown bound.
3564 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3565 Self.RequireCompleteType(KeyLoc, LhsT,
3566 diag::err_incomplete_type_used_in_type_trait_expr))
3568 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3569 Self.RequireCompleteType(KeyLoc, RhsT,
3570 diag::err_incomplete_type_used_in_type_trait_expr))
3573 // cv void is never assignable.
3574 if (LhsT->isVoidType() || RhsT->isVoidType())
3577 // Build expressions that emulate the effect of declval<T>() and
3579 if (LhsT->isObjectType() || LhsT->isFunctionType())
3580 LhsT = Self.Context.getRValueReferenceType(LhsT);
3581 if (RhsT->isObjectType() || RhsT->isFunctionType())
3582 RhsT = Self.Context.getRValueReferenceType(RhsT);
3583 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3584 Expr::getValueKindForType(LhsT));
3585 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3586 Expr::getValueKindForType(RhsT));
3588 // Attempt the assignment in an unevaluated context within a SFINAE
3589 // trap at translation unit scope.
3590 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3591 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3592 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3593 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3594 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3597 // Under Objective-C ARC, if the destination has non-trivial Objective-C
3598 // lifetime, this is a non-trivial assignment.
3599 if (Self.getLangOpts().ObjCAutoRefCount &&
3600 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
3603 return !Result.get()->hasNonTrivialCall(Self.Context);
3606 llvm_unreachable("Unknown type trait or not implemented");
3609 ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3610 SourceLocation KWLoc,
3611 TypeSourceInfo *LhsTSInfo,
3612 TypeSourceInfo *RhsTSInfo,
3613 SourceLocation RParen) {
3614 QualType LhsT = LhsTSInfo->getType();
3615 QualType RhsT = RhsTSInfo->getType();
3617 if (BTT == BTT_TypeCompatible) {
3618 if (getLangOpts().CPlusPlus) {
3619 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3620 << SourceRange(KWLoc, RParen);
3626 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3627 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3629 // Select trait result type.
3630 QualType ResultType;
3632 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
3633 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3634 case BTT_IsSame: ResultType = Context.BoolTy; break;
3635 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
3636 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
3637 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
3640 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3641 RhsTSInfo, Value, RParen,
3645 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3646 SourceLocation KWLoc,
3649 SourceLocation RParen) {
3650 TypeSourceInfo *TSInfo;
3651 QualType T = GetTypeFromParser(Ty, &TSInfo);
3653 TSInfo = Context.getTrivialTypeSourceInfo(T);
3655 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3658 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3659 QualType T, Expr *DimExpr,
3660 SourceLocation KeyLoc) {
3661 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3665 if (T->isArrayType()) {
3667 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3669 T = AT->getElementType();
3675 case ATT_ArrayExtent: {
3678 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3679 diag::err_dimension_expr_not_constant_integer,
3682 if (Value.isSigned() && Value.isNegative()) {
3683 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3684 << DimExpr->getSourceRange();
3687 Dim = Value.getLimitedValue();
3689 if (T->isArrayType()) {
3691 bool Matched = false;
3692 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3698 T = AT->getElementType();
3701 if (Matched && T->isArrayType()) {
3702 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3703 return CAT->getSize().getLimitedValue();
3709 llvm_unreachable("Unknown type trait or not implemented");
3712 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3713 SourceLocation KWLoc,
3714 TypeSourceInfo *TSInfo,
3716 SourceLocation RParen) {
3717 QualType T = TSInfo->getType();
3719 // FIXME: This should likely be tracked as an APInt to remove any host
3720 // assumptions about the width of size_t on the target.
3722 if (!T->isDependentType())
3723 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3725 // While the specification for these traits from the Embarcadero C++
3726 // compiler's documentation says the return type is 'unsigned int', Clang
3727 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3728 // compiler, there is no difference. On several other platforms this is an
3729 // important distinction.
3730 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
3732 Context.getSizeType()));
3735 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
3736 SourceLocation KWLoc,
3738 SourceLocation RParen) {
3739 // If error parsing the expression, ignore.
3743 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
3748 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3750 case ET_IsLValueExpr: return E->isLValue();
3751 case ET_IsRValueExpr: return E->isRValue();
3753 llvm_unreachable("Expression trait not covered by switch");
3756 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
3757 SourceLocation KWLoc,
3759 SourceLocation RParen) {
3760 if (Queried->isTypeDependent()) {
3761 // Delay type-checking for type-dependent expressions.
3762 } else if (Queried->getType()->isPlaceholderType()) {
3763 ExprResult PE = CheckPlaceholderExpr(Queried);
3764 if (PE.isInvalid()) return ExprError();
3765 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3768 bool Value = EvaluateExpressionTrait(ET, Queried);
3770 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3771 RParen, Context.BoolTy));
3774 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
3778 assert(!LHS.get()->getType()->isPlaceholderType() &&
3779 !RHS.get()->getType()->isPlaceholderType() &&
3780 "placeholders should have been weeded out by now");
3782 // The LHS undergoes lvalue conversions if this is ->*.
3784 LHS = DefaultLvalueConversion(LHS.take());
3785 if (LHS.isInvalid()) return QualType();
3788 // The RHS always undergoes lvalue conversions.
3789 RHS = DefaultLvalueConversion(RHS.take());
3790 if (RHS.isInvalid()) return QualType();
3792 const char *OpSpelling = isIndirect ? "->*" : ".*";
3794 // The binary operator .* [p3: ->*] binds its second operand, which shall
3795 // be of type "pointer to member of T" (where T is a completely-defined
3796 // class type) [...]
3797 QualType RHSType = RHS.get()->getType();
3798 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
3800 Diag(Loc, diag::err_bad_memptr_rhs)
3801 << OpSpelling << RHSType << RHS.get()->getSourceRange();
3805 QualType Class(MemPtr->getClass(), 0);
3807 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3808 // member pointer points must be completely-defined. However, there is no
3809 // reason for this semantic distinction, and the rule is not enforced by
3810 // other compilers. Therefore, we do not check this property, as it is
3811 // likely to be considered a defect.
3814 // [...] to its first operand, which shall be of class T or of a class of
3815 // which T is an unambiguous and accessible base class. [p3: a pointer to
3817 QualType LHSType = LHS.get()->getType();
3819 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3820 LHSType = Ptr->getPointeeType();
3822 Diag(Loc, diag::err_bad_memptr_lhs)
3823 << OpSpelling << 1 << LHSType
3824 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
3829 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
3830 // If we want to check the hierarchy, we need a complete type.
3831 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
3832 OpSpelling, (int)isIndirect)) {
3835 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3836 /*DetectVirtual=*/false);
3837 // FIXME: Would it be useful to print full ambiguity paths, or is that
3839 if (!IsDerivedFrom(LHSType, Class, Paths) ||
3840 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3841 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
3842 << (int)isIndirect << LHS.get()->getType();
3845 // Cast LHS to type of use.
3846 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
3847 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
3849 CXXCastPath BasePath;
3850 BuildBasePathArray(Paths, BasePath);
3851 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3855 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
3856 // Diagnose use of pointer-to-member type which when used as
3857 // the functional cast in a pointer-to-member expression.
3858 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3863 // The result is an object or a function of the type specified by the
3865 // The cv qualifiers are the union of those in the pointer and the left side,
3866 // in accordance with 5.5p5 and 5.2.5.
3867 QualType Result = MemPtr->getPointeeType();
3868 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
3870 // C++0x [expr.mptr.oper]p6:
3871 // In a .* expression whose object expression is an rvalue, the program is
3872 // ill-formed if the second operand is a pointer to member function with
3873 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3874 // expression is an lvalue, the program is ill-formed if the second operand
3875 // is a pointer to member function with ref-qualifier &&.
3876 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3877 switch (Proto->getRefQualifier()) {
3883 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
3884 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3885 << RHSType << 1 << LHS.get()->getSourceRange();
3889 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
3890 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3891 << RHSType << 0 << LHS.get()->getSourceRange();
3896 // C++ [expr.mptr.oper]p6:
3897 // The result of a .* expression whose second operand is a pointer
3898 // to a data member is of the same value category as its
3899 // first operand. The result of a .* expression whose second
3900 // operand is a pointer to a member function is a prvalue. The
3901 // result of an ->* expression is an lvalue if its second operand
3902 // is a pointer to data member and a prvalue otherwise.
3903 if (Result->isFunctionType()) {
3905 return Context.BoundMemberTy;
3906 } else if (isIndirect) {
3909 VK = LHS.get()->getValueKind();
3915 /// \brief Try to convert a type to another according to C++0x 5.16p3.
3917 /// This is part of the parameter validation for the ? operator. If either
3918 /// value operand is a class type, the two operands are attempted to be
3919 /// converted to each other. This function does the conversion in one direction.
3920 /// It returns true if the program is ill-formed and has already been diagnosed
3922 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3923 SourceLocation QuestionLoc,
3924 bool &HaveConversion,
3926 HaveConversion = false;
3927 ToType = To->getType();
3929 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
3932 // The process for determining whether an operand expression E1 of type T1
3933 // can be converted to match an operand expression E2 of type T2 is defined
3935 // -- If E2 is an lvalue:
3936 bool ToIsLvalue = To->isLValue();
3938 // E1 can be converted to match E2 if E1 can be implicitly converted to
3939 // type "lvalue reference to T2", subject to the constraint that in the
3940 // conversion the reference must bind directly to E1.
3941 QualType T = Self.Context.getLValueReferenceType(ToType);
3942 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3944 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3945 if (InitSeq.isDirectReferenceBinding()) {
3947 HaveConversion = true;
3951 if (InitSeq.isAmbiguous())
3952 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3955 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3956 // -- if E1 and E2 have class type, and the underlying class types are
3957 // the same or one is a base class of the other:
3958 QualType FTy = From->getType();
3959 QualType TTy = To->getType();
3960 const RecordType *FRec = FTy->getAs<RecordType>();
3961 const RecordType *TRec = TTy->getAs<RecordType>();
3962 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
3963 Self.IsDerivedFrom(FTy, TTy);
3965 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
3966 // E1 can be converted to match E2 if the class of T2 is the
3967 // same type as, or a base class of, the class of T1, and
3969 if (FRec == TRec || FDerivedFromT) {
3970 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
3971 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3972 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3974 HaveConversion = true;
3978 if (InitSeq.isAmbiguous())
3979 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3986 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3987 // implicitly converted to the type that expression E2 would have
3988 // if E2 were converted to an rvalue (or the type it has, if E2 is
3991 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3992 // to the array-to-pointer or function-to-pointer conversions.
3993 if (!TTy->getAs<TagType>())
3994 TTy = TTy.getUnqualifiedType();
3996 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3997 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3998 HaveConversion = !InitSeq.Failed();
4000 if (InitSeq.isAmbiguous())
4001 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
4006 /// \brief Try to find a common type for two according to C++0x 5.16p5.
4008 /// This is part of the parameter validation for the ? operator. If either
4009 /// value operand is a class type, overload resolution is used to find a
4010 /// conversion to a common type.
4011 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
4012 SourceLocation QuestionLoc) {
4013 Expr *Args[2] = { LHS.get(), RHS.get() };
4014 OverloadCandidateSet CandidateSet(QuestionLoc);
4015 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
4018 OverloadCandidateSet::iterator Best;
4019 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
4021 // We found a match. Perform the conversions on the arguments and move on.
4023 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4024 Best->Conversions[0], Sema::AA_Converting);
4025 if (LHSRes.isInvalid())
4030 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4031 Best->Conversions[1], Sema::AA_Converting);
4032 if (RHSRes.isInvalid())
4036 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
4040 case OR_No_Viable_Function:
4042 // Emit a better diagnostic if one of the expressions is a null pointer
4043 // constant and the other is a pointer type. In this case, the user most
4044 // likely forgot to take the address of the other expression.
4045 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4048 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4049 << LHS.get()->getType() << RHS.get()->getType()
4050 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4054 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
4055 << LHS.get()->getType() << RHS.get()->getType()
4056 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4057 // FIXME: Print the possible common types by printing the return types of
4058 // the viable candidates.
4062 llvm_unreachable("Conditional operator has only built-in overloads");
4067 /// \brief Perform an "extended" implicit conversion as returned by
4068 /// TryClassUnification.
4069 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
4070 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4071 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
4073 Expr *Arg = E.take();
4074 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
4075 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
4076 if (Result.isInvalid())
4083 /// \brief Check the operands of ?: under C++ semantics.
4085 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4086 /// extension. In this case, LHS == Cond. (But they're not aliases.)
4087 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4088 ExprResult &RHS, ExprValueKind &VK,
4090 SourceLocation QuestionLoc) {
4091 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4092 // interface pointers.
4094 // C++11 [expr.cond]p1
4095 // The first expression is contextually converted to bool.
4096 if (!Cond.get()->isTypeDependent()) {
4097 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4098 if (CondRes.isInvalid())
4107 // Either of the arguments dependent?
4108 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
4109 return Context.DependentTy;
4111 // C++11 [expr.cond]p2
4112 // If either the second or the third operand has type (cv) void, ...
4113 QualType LTy = LHS.get()->getType();
4114 QualType RTy = RHS.get()->getType();
4115 bool LVoid = LTy->isVoidType();
4116 bool RVoid = RTy->isVoidType();
4117 if (LVoid || RVoid) {
4118 // ... then the [l2r] conversions are performed on the second and third
4120 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4121 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4122 if (LHS.isInvalid() || RHS.isInvalid())
4125 // Finish off the lvalue-to-rvalue conversion by copy-initializing a
4126 // temporary if necessary. DefaultFunctionArrayLvalueConversion doesn't
4127 // do this part for us.
4128 ExprResult &NonVoid = LVoid ? RHS : LHS;
4129 if (NonVoid.get()->getType()->isRecordType() &&
4130 NonVoid.get()->isGLValue()) {
4131 if (RequireNonAbstractType(QuestionLoc, NonVoid.get()->getType(),
4132 diag::err_allocation_of_abstract_type))
4134 InitializedEntity Entity =
4135 InitializedEntity::InitializeTemporary(NonVoid.get()->getType());
4136 NonVoid = PerformCopyInitialization(Entity, SourceLocation(), NonVoid);
4137 if (NonVoid.isInvalid())
4141 LTy = LHS.get()->getType();
4142 RTy = RHS.get()->getType();
4144 // ... and one of the following shall hold:
4145 // -- The second or the third operand (but not both) is a throw-
4146 // expression; the result is of the type of the other and is a prvalue.
4147 bool LThrow = isa<CXXThrowExpr>(LHS.get());
4148 bool RThrow = isa<CXXThrowExpr>(RHS.get());
4149 if (LThrow && !RThrow)
4151 if (RThrow && !LThrow)
4154 // -- Both the second and third operands have type void; the result is of
4155 // type void and is a prvalue.
4157 return Context.VoidTy;
4159 // Neither holds, error.
4160 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4161 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
4162 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4168 // C++11 [expr.cond]p3
4169 // Otherwise, if the second and third operand have different types, and
4170 // either has (cv) class type [...] an attempt is made to convert each of
4171 // those operands to the type of the other.
4172 if (!Context.hasSameType(LTy, RTy) &&
4173 (LTy->isRecordType() || RTy->isRecordType())) {
4174 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4175 // These return true if a single direction is already ambiguous.
4176 QualType L2RType, R2LType;
4177 bool HaveL2R, HaveR2L;
4178 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
4180 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
4183 // If both can be converted, [...] the program is ill-formed.
4184 if (HaveL2R && HaveR2L) {
4185 Diag(QuestionLoc, diag::err_conditional_ambiguous)
4186 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4190 // If exactly one conversion is possible, that conversion is applied to
4191 // the chosen operand and the converted operands are used in place of the
4192 // original operands for the remainder of this section.
4194 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
4196 LTy = LHS.get()->getType();
4197 } else if (HaveR2L) {
4198 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
4200 RTy = RHS.get()->getType();
4204 // C++11 [expr.cond]p3
4205 // if both are glvalues of the same value category and the same type except
4206 // for cv-qualification, an attempt is made to convert each of those
4207 // operands to the type of the other.
4208 ExprValueKind LVK = LHS.get()->getValueKind();
4209 ExprValueKind RVK = RHS.get()->getValueKind();
4210 if (!Context.hasSameType(LTy, RTy) &&
4211 Context.hasSameUnqualifiedType(LTy, RTy) &&
4212 LVK == RVK && LVK != VK_RValue) {
4213 // Since the unqualified types are reference-related and we require the
4214 // result to be as if a reference bound directly, the only conversion
4215 // we can perform is to add cv-qualifiers.
4216 Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
4217 Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
4218 if (RCVR.isStrictSupersetOf(LCVR)) {
4219 LHS = ImpCastExprToType(LHS.take(), RTy, CK_NoOp, LVK);
4220 LTy = LHS.get()->getType();
4222 else if (LCVR.isStrictSupersetOf(RCVR)) {
4223 RHS = ImpCastExprToType(RHS.take(), LTy, CK_NoOp, RVK);
4224 RTy = RHS.get()->getType();
4228 // C++11 [expr.cond]p4
4229 // If the second and third operands are glvalues of the same value
4230 // category and have the same type, the result is of that type and
4231 // value category and it is a bit-field if the second or the third
4232 // operand is a bit-field, or if both are bit-fields.
4233 // We only extend this to bitfields, not to the crazy other kinds of
4235 bool Same = Context.hasSameType(LTy, RTy);
4236 if (Same && LVK == RVK && LVK != VK_RValue &&
4237 LHS.get()->isOrdinaryOrBitFieldObject() &&
4238 RHS.get()->isOrdinaryOrBitFieldObject()) {
4239 VK = LHS.get()->getValueKind();
4240 if (LHS.get()->getObjectKind() == OK_BitField ||
4241 RHS.get()->getObjectKind() == OK_BitField)
4246 // C++11 [expr.cond]p5
4247 // Otherwise, the result is a prvalue. If the second and third operands
4248 // do not have the same type, and either has (cv) class type, ...
4249 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4250 // ... overload resolution is used to determine the conversions (if any)
4251 // to be applied to the operands. If the overload resolution fails, the
4252 // program is ill-formed.
4253 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4257 // C++11 [expr.cond]p6
4258 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
4259 // conversions are performed on the second and third operands.
4260 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4261 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4262 if (LHS.isInvalid() || RHS.isInvalid())
4264 LTy = LHS.get()->getType();
4265 RTy = RHS.get()->getType();
4267 // After those conversions, one of the following shall hold:
4268 // -- The second and third operands have the same type; the result
4269 // is of that type. If the operands have class type, the result
4270 // is a prvalue temporary of the result type, which is
4271 // copy-initialized from either the second operand or the third
4272 // operand depending on the value of the first operand.
4273 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4274 if (LTy->isRecordType()) {
4275 // The operands have class type. Make a temporary copy.
4276 if (RequireNonAbstractType(QuestionLoc, LTy,
4277 diag::err_allocation_of_abstract_type))
4279 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
4281 ExprResult LHSCopy = PerformCopyInitialization(Entity,
4284 if (LHSCopy.isInvalid())
4287 ExprResult RHSCopy = PerformCopyInitialization(Entity,
4290 if (RHSCopy.isInvalid())
4300 // Extension: conditional operator involving vector types.
4301 if (LTy->isVectorType() || RTy->isVectorType())
4302 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4304 // -- The second and third operands have arithmetic or enumeration type;
4305 // the usual arithmetic conversions are performed to bring them to a
4306 // common type, and the result is of that type.
4307 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4308 UsualArithmeticConversions(LHS, RHS);
4309 if (LHS.isInvalid() || RHS.isInvalid())
4311 return LHS.get()->getType();
4314 // -- The second and third operands have pointer type, or one has pointer
4315 // type and the other is a null pointer constant, or both are null
4316 // pointer constants, at least one of which is non-integral; pointer
4317 // conversions and qualification conversions are performed to bring them
4318 // to their composite pointer type. The result is of the composite
4320 // -- The second and third operands have pointer to member type, or one has
4321 // pointer to member type and the other is a null pointer constant;
4322 // pointer to member conversions and qualification conversions are
4323 // performed to bring them to a common type, whose cv-qualification
4324 // shall match the cv-qualification of either the second or the third
4325 // operand. The result is of the common type.
4326 bool NonStandardCompositeType = false;
4327 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
4328 isSFINAEContext()? 0 : &NonStandardCompositeType);
4329 if (!Composite.isNull()) {
4330 if (NonStandardCompositeType)
4332 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4333 << LTy << RTy << Composite
4334 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4339 // Similarly, attempt to find composite type of two objective-c pointers.
4340 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4341 if (!Composite.isNull())
4344 // Check if we are using a null with a non-pointer type.
4345 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4348 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4349 << LHS.get()->getType() << RHS.get()->getType()
4350 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4354 /// \brief Find a merged pointer type and convert the two expressions to it.
4356 /// This finds the composite pointer type (or member pointer type) for @p E1
4357 /// and @p E2 according to C++11 5.9p2. It converts both expressions to this
4358 /// type and returns it.
4359 /// It does not emit diagnostics.
4361 /// \param Loc The location of the operator requiring these two expressions to
4362 /// be converted to the composite pointer type.
4364 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4365 /// a non-standard (but still sane) composite type to which both expressions
4366 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4367 /// will be set true.
4368 QualType Sema::FindCompositePointerType(SourceLocation Loc,
4369 Expr *&E1, Expr *&E2,
4370 bool *NonStandardCompositeType) {
4371 if (NonStandardCompositeType)
4372 *NonStandardCompositeType = false;
4374 assert(getLangOpts().CPlusPlus && "This function assumes C++");
4375 QualType T1 = E1->getType(), T2 = E2->getType();
4378 // Pointer conversions and qualification conversions are performed on
4379 // pointer operands to bring them to their composite pointer type. If
4380 // one operand is a null pointer constant, the composite pointer type is
4381 // std::nullptr_t if the other operand is also a null pointer constant or,
4382 // if the other operand is a pointer, the type of the other operand.
4383 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4384 !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
4385 if (T1->isNullPtrType() &&
4386 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4387 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
4390 if (T2->isNullPtrType() &&
4391 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4392 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
4398 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4399 if (T2->isMemberPointerType())
4400 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
4402 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
4405 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4406 if (T1->isMemberPointerType())
4407 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
4409 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
4413 // Now both have to be pointers or member pointers.
4414 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4415 (!T2->isPointerType() && !T2->isMemberPointerType()))
4418 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4419 // the other has type "pointer to cv2 T" and the composite pointer type is
4420 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4421 // Otherwise, the composite pointer type is a pointer type similar to the
4422 // type of one of the operands, with a cv-qualification signature that is
4423 // the union of the cv-qualification signatures of the operand types.
4424 // In practice, the first part here is redundant; it's subsumed by the second.
4425 // What we do here is, we build the two possible composite types, and try the
4426 // conversions in both directions. If only one works, or if the two composite
4427 // types are the same, we have succeeded.
4428 // FIXME: extended qualifiers?
4429 typedef SmallVector<unsigned, 4> QualifierVector;
4430 QualifierVector QualifierUnion;
4431 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
4432 ContainingClassVector;
4433 ContainingClassVector MemberOfClass;
4434 QualType Composite1 = Context.getCanonicalType(T1),
4435 Composite2 = Context.getCanonicalType(T2);
4436 unsigned NeedConstBefore = 0;
4438 const PointerType *Ptr1, *Ptr2;
4439 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4440 (Ptr2 = Composite2->getAs<PointerType>())) {
4441 Composite1 = Ptr1->getPointeeType();
4442 Composite2 = Ptr2->getPointeeType();
4444 // If we're allowed to create a non-standard composite type, keep track
4445 // of where we need to fill in additional 'const' qualifiers.
4446 if (NonStandardCompositeType &&
4447 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4448 NeedConstBefore = QualifierUnion.size();
4450 QualifierUnion.push_back(
4451 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4452 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4456 const MemberPointerType *MemPtr1, *MemPtr2;
4457 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4458 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4459 Composite1 = MemPtr1->getPointeeType();
4460 Composite2 = MemPtr2->getPointeeType();
4462 // If we're allowed to create a non-standard composite type, keep track
4463 // of where we need to fill in additional 'const' qualifiers.
4464 if (NonStandardCompositeType &&
4465 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4466 NeedConstBefore = QualifierUnion.size();
4468 QualifierUnion.push_back(
4469 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4470 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4471 MemPtr2->getClass()));
4475 // FIXME: block pointer types?
4477 // Cannot unwrap any more types.
4481 if (NeedConstBefore && NonStandardCompositeType) {
4482 // Extension: Add 'const' to qualifiers that come before the first qualifier
4483 // mismatch, so that our (non-standard!) composite type meets the
4484 // requirements of C++ [conv.qual]p4 bullet 3.
4485 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4486 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4487 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4488 *NonStandardCompositeType = true;
4493 // Rewrap the composites as pointers or member pointers with the union CVRs.
4494 ContainingClassVector::reverse_iterator MOC
4495 = MemberOfClass.rbegin();
4496 for (QualifierVector::reverse_iterator
4497 I = QualifierUnion.rbegin(),
4498 E = QualifierUnion.rend();
4499 I != E; (void)++I, ++MOC) {
4500 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
4501 if (MOC->first && MOC->second) {
4502 // Rebuild member pointer type
4503 Composite1 = Context.getMemberPointerType(
4504 Context.getQualifiedType(Composite1, Quals),
4506 Composite2 = Context.getMemberPointerType(
4507 Context.getQualifiedType(Composite2, Quals),
4510 // Rebuild pointer type
4512 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4514 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
4518 // Try to convert to the first composite pointer type.
4519 InitializedEntity Entity1
4520 = InitializedEntity::InitializeTemporary(Composite1);
4521 InitializationKind Kind
4522 = InitializationKind::CreateCopy(Loc, SourceLocation());
4523 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4524 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
4526 if (E1ToC1 && E2ToC1) {
4527 // Conversion to Composite1 is viable.
4528 if (!Context.hasSameType(Composite1, Composite2)) {
4529 // Composite2 is a different type from Composite1. Check whether
4530 // Composite2 is also viable.
4531 InitializedEntity Entity2
4532 = InitializedEntity::InitializeTemporary(Composite2);
4533 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4534 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4535 if (E1ToC2 && E2ToC2) {
4536 // Both Composite1 and Composite2 are viable and are different;
4537 // this is an ambiguity.
4542 // Convert E1 to Composite1
4544 = E1ToC1.Perform(*this, Entity1, Kind, E1);
4545 if (E1Result.isInvalid())
4547 E1 = E1Result.takeAs<Expr>();
4549 // Convert E2 to Composite1
4551 = E2ToC1.Perform(*this, Entity1, Kind, E2);
4552 if (E2Result.isInvalid())
4554 E2 = E2Result.takeAs<Expr>();
4559 // Check whether Composite2 is viable.
4560 InitializedEntity Entity2
4561 = InitializedEntity::InitializeTemporary(Composite2);
4562 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4563 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4564 if (!E1ToC2 || !E2ToC2)
4567 // Convert E1 to Composite2
4569 = E1ToC2.Perform(*this, Entity2, Kind, E1);
4570 if (E1Result.isInvalid())
4572 E1 = E1Result.takeAs<Expr>();
4574 // Convert E2 to Composite2
4576 = E2ToC2.Perform(*this, Entity2, Kind, E2);
4577 if (E2Result.isInvalid())
4579 E2 = E2Result.takeAs<Expr>();
4584 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
4588 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4590 // If the result is a glvalue, we shouldn't bind it.
4594 // In ARC, calls that return a retainable type can return retained,
4595 // in which case we have to insert a consuming cast.
4596 if (getLangOpts().ObjCAutoRefCount &&
4597 E->getType()->isObjCRetainableType()) {
4599 bool ReturnsRetained;
4601 // For actual calls, we compute this by examining the type of the
4603 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4604 Expr *Callee = Call->getCallee()->IgnoreParens();
4605 QualType T = Callee->getType();
4607 if (T == Context.BoundMemberTy) {
4608 // Handle pointer-to-members.
4609 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4610 T = BinOp->getRHS()->getType();
4611 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4612 T = Mem->getMemberDecl()->getType();
4615 if (const PointerType *Ptr = T->getAs<PointerType>())
4616 T = Ptr->getPointeeType();
4617 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4618 T = Ptr->getPointeeType();
4619 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4620 T = MemPtr->getPointeeType();
4622 const FunctionType *FTy = T->getAs<FunctionType>();
4623 assert(FTy && "call to value not of function type?");
4624 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4626 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4627 // type always produce a +1 object.
4628 } else if (isa<StmtExpr>(E)) {
4629 ReturnsRetained = true;
4631 // We hit this case with the lambda conversion-to-block optimization;
4632 // we don't want any extra casts here.
4633 } else if (isa<CastExpr>(E) &&
4634 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4637 // For message sends and property references, we try to find an
4638 // actual method. FIXME: we should infer retention by selector in
4639 // cases where we don't have an actual method.
4641 ObjCMethodDecl *D = 0;
4642 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4643 D = Send->getMethodDecl();
4644 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4645 D = BoxedExpr->getBoxingMethod();
4646 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4647 D = ArrayLit->getArrayWithObjectsMethod();
4648 } else if (ObjCDictionaryLiteral *DictLit
4649 = dyn_cast<ObjCDictionaryLiteral>(E)) {
4650 D = DictLit->getDictWithObjectsMethod();
4653 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
4655 // Don't do reclaims on performSelector calls; despite their
4656 // return type, the invoked method doesn't necessarily actually
4657 // return an object.
4658 if (!ReturnsRetained &&
4659 D && D->getMethodFamily() == OMF_performSelector)
4663 // Don't reclaim an object of Class type.
4664 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4667 ExprNeedsCleanups = true;
4669 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4670 : CK_ARCReclaimReturnedObject);
4671 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4675 if (!getLangOpts().CPlusPlus)
4678 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4679 // a fast path for the common case that the type is directly a RecordType.
4680 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4681 const RecordType *RT = 0;
4683 switch (T->getTypeClass()) {
4685 RT = cast<RecordType>(T);
4687 case Type::ConstantArray:
4688 case Type::IncompleteArray:
4689 case Type::VariableArray:
4690 case Type::DependentSizedArray:
4691 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4698 // That should be enough to guarantee that this type is complete, if we're
4699 // not processing a decltype expression.
4700 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4701 if (RD->isInvalidDecl() || RD->isDependentContext())
4704 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4705 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
4708 MarkFunctionReferenced(E->getExprLoc(), Destructor);
4709 CheckDestructorAccess(E->getExprLoc(), Destructor,
4710 PDiag(diag::err_access_dtor_temp)
4712 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
4714 // If destructor is trivial, we can avoid the extra copy.
4715 if (Destructor->isTrivial())
4718 // We need a cleanup, but we don't need to remember the temporary.
4719 ExprNeedsCleanups = true;
4722 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4723 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4726 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4732 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
4733 if (SubExpr.isInvalid())
4736 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
4739 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4740 assert(SubExpr && "sub expression can't be null!");
4742 CleanupVarDeclMarking();
4744 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4745 assert(ExprCleanupObjects.size() >= FirstCleanup);
4746 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4747 if (!ExprNeedsCleanups)
4750 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4751 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4752 ExprCleanupObjects.size() - FirstCleanup);
4754 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4755 DiscardCleanupsInEvaluationContext();
4760 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
4761 assert(SubStmt && "sub statement can't be null!");
4763 CleanupVarDeclMarking();
4765 if (!ExprNeedsCleanups)
4768 // FIXME: In order to attach the temporaries, wrap the statement into
4769 // a StmtExpr; currently this is only used for asm statements.
4770 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4771 // a new AsmStmtWithTemporaries.
4772 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4775 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4777 return MaybeCreateExprWithCleanups(E);
4780 /// Process the expression contained within a decltype. For such expressions,
4781 /// certain semantic checks on temporaries are delayed until this point, and
4782 /// are omitted for the 'topmost' call in the decltype expression. If the
4783 /// topmost call bound a temporary, strip that temporary off the expression.
4784 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
4785 ExpressionEvaluationContextRecord &Rec = ExprEvalContexts.back();
4786 assert(Rec.IsDecltype && "not in a decltype expression");
4788 // C++11 [expr.call]p11:
4789 // If a function call is a prvalue of object type,
4790 // -- if the function call is either
4791 // -- the operand of a decltype-specifier, or
4792 // -- the right operand of a comma operator that is the operand of a
4793 // decltype-specifier,
4794 // a temporary object is not introduced for the prvalue.
4796 // Recursively rebuild ParenExprs and comma expressions to strip out the
4797 // outermost CXXBindTemporaryExpr, if any.
4798 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4799 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
4800 if (SubExpr.isInvalid())
4802 if (SubExpr.get() == PE->getSubExpr())
4804 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
4806 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4807 if (BO->getOpcode() == BO_Comma) {
4808 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
4809 if (RHS.isInvalid())
4811 if (RHS.get() == BO->getRHS())
4813 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
4814 BO_Comma, BO->getType(),
4816 BO->getObjectKind(),
4817 BO->getOperatorLoc(),
4818 BO->isFPContractable()));
4822 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
4824 E = TopBind->getSubExpr();
4826 // Disable the special decltype handling now.
4827 Rec.IsDecltype = false;
4829 // In MS mode, don't perform any extra checking of call return types within a
4830 // decltype expression.
4831 if (getLangOpts().MicrosoftMode)
4834 // Perform the semantic checks we delayed until this point.
4835 CallExpr *TopCall = dyn_cast<CallExpr>(E);
4836 for (unsigned I = 0, N = Rec.DelayedDecltypeCalls.size(); I != N; ++I) {
4837 CallExpr *Call = Rec.DelayedDecltypeCalls[I];
4838 if (Call == TopCall)
4841 if (CheckCallReturnType(Call->getCallReturnType(),
4842 Call->getLocStart(),
4843 Call, Call->getDirectCallee()))
4847 // Now all relevant types are complete, check the destructors are accessible
4848 // and non-deleted, and annotate them on the temporaries.
4849 for (unsigned I = 0, N = Rec.DelayedDecltypeBinds.size(); I != N; ++I) {
4850 CXXBindTemporaryExpr *Bind = Rec.DelayedDecltypeBinds[I];
4851 if (Bind == TopBind)
4854 CXXTemporary *Temp = Bind->getTemporary();
4857 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
4858 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4859 Temp->setDestructor(Destructor);
4861 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
4862 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
4863 PDiag(diag::err_access_dtor_temp)
4864 << Bind->getType());
4865 DiagnoseUseOfDecl(Destructor, Bind->getExprLoc());
4867 // We need a cleanup, but we don't need to remember the temporary.
4868 ExprNeedsCleanups = true;
4871 // Possibly strip off the top CXXBindTemporaryExpr.
4876 Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
4877 tok::TokenKind OpKind, ParsedType &ObjectType,
4878 bool &MayBePseudoDestructor) {
4879 // Since this might be a postfix expression, get rid of ParenListExprs.
4880 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
4881 if (Result.isInvalid()) return ExprError();
4882 Base = Result.get();
4884 Result = CheckPlaceholderExpr(Base);
4885 if (Result.isInvalid()) return ExprError();
4886 Base = Result.take();
4888 QualType BaseType = Base->getType();
4889 MayBePseudoDestructor = false;
4890 if (BaseType->isDependentType()) {
4891 // If we have a pointer to a dependent type and are using the -> operator,
4892 // the object type is the type that the pointer points to. We might still
4893 // have enough information about that type to do something useful.
4894 if (OpKind == tok::arrow)
4895 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4896 BaseType = Ptr->getPointeeType();
4898 ObjectType = ParsedType::make(BaseType);
4899 MayBePseudoDestructor = true;
4903 // C++ [over.match.oper]p8:
4904 // [...] When operator->returns, the operator-> is applied to the value
4905 // returned, with the original second operand.
4906 if (OpKind == tok::arrow) {
4907 // The set of types we've considered so far.
4908 llvm::SmallPtrSet<CanQualType,8> CTypes;
4909 SmallVector<SourceLocation, 8> Locations;
4910 CTypes.insert(Context.getCanonicalType(BaseType));
4912 while (BaseType->isRecordType()) {
4913 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4914 if (Result.isInvalid())
4916 Base = Result.get();
4917 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
4918 Locations.push_back(OpCall->getDirectCallee()->getLocation());
4919 BaseType = Base->getType();
4920 CanQualType CBaseType = Context.getCanonicalType(BaseType);
4921 if (!CTypes.insert(CBaseType)) {
4922 Diag(OpLoc, diag::err_operator_arrow_circular);
4923 for (unsigned i = 0; i < Locations.size(); i++)
4924 Diag(Locations[i], diag::note_declared_at);
4929 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
4930 BaseType = BaseType->getPointeeType();
4933 // Objective-C properties allow "." access on Objective-C pointer types,
4934 // so adjust the base type to the object type itself.
4935 if (BaseType->isObjCObjectPointerType())
4936 BaseType = BaseType->getPointeeType();
4938 // C++ [basic.lookup.classref]p2:
4939 // [...] If the type of the object expression is of pointer to scalar
4940 // type, the unqualified-id is looked up in the context of the complete
4941 // postfix-expression.
4943 // This also indicates that we could be parsing a pseudo-destructor-name.
4944 // Note that Objective-C class and object types can be pseudo-destructor
4945 // expressions or normal member (ivar or property) access expressions.
4946 if (BaseType->isObjCObjectOrInterfaceType()) {
4947 MayBePseudoDestructor = true;
4948 } else if (!BaseType->isRecordType()) {
4949 ObjectType = ParsedType();
4950 MayBePseudoDestructor = true;
4954 // The object type must be complete (or dependent), or
4955 // C++11 [expr.prim.general]p3:
4956 // Unlike the object expression in other contexts, *this is not required to
4957 // be of complete type for purposes of class member access (5.2.5) outside
4958 // the member function body.
4959 if (!BaseType->isDependentType() &&
4960 !isThisOutsideMemberFunctionBody(BaseType) &&
4961 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
4964 // C++ [basic.lookup.classref]p2:
4965 // If the id-expression in a class member access (5.2.5) is an
4966 // unqualified-id, and the type of the object expression is of a class
4967 // type C (or of pointer to a class type C), the unqualified-id is looked
4968 // up in the scope of class C. [...]
4969 ObjectType = ParsedType::make(BaseType);
4973 ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
4975 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
4976 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4977 << isa<CXXPseudoDestructorExpr>(MemExpr)
4978 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
4980 return ActOnCallExpr(/*Scope*/ 0,
4982 /*LPLoc*/ ExpectedLParenLoc,
4984 /*RPLoc*/ ExpectedLParenLoc);
4987 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
4988 tok::TokenKind& OpKind, SourceLocation OpLoc) {
4989 if (Base->hasPlaceholderType()) {
4990 ExprResult result = S.CheckPlaceholderExpr(Base);
4991 if (result.isInvalid()) return true;
4992 Base = result.take();
4994 ObjectType = Base->getType();
4996 // C++ [expr.pseudo]p2:
4997 // The left-hand side of the dot operator shall be of scalar type. The
4998 // left-hand side of the arrow operator shall be of pointer to scalar type.
4999 // This scalar type is the object type.
5000 // Note that this is rather different from the normal handling for the
5002 if (OpKind == tok::arrow) {
5003 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
5004 ObjectType = Ptr->getPointeeType();
5005 } else if (!Base->isTypeDependent()) {
5006 // The user wrote "p->" when she probably meant "p."; fix it.
5007 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5008 << ObjectType << true
5009 << FixItHint::CreateReplacement(OpLoc, ".");
5010 if (S.isSFINAEContext())
5013 OpKind = tok::period;
5020 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
5021 SourceLocation OpLoc,
5022 tok::TokenKind OpKind,
5023 const CXXScopeSpec &SS,
5024 TypeSourceInfo *ScopeTypeInfo,
5025 SourceLocation CCLoc,
5026 SourceLocation TildeLoc,
5027 PseudoDestructorTypeStorage Destructed,
5028 bool HasTrailingLParen) {
5029 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
5031 QualType ObjectType;
5032 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5035 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
5036 !ObjectType->isVectorType()) {
5037 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
5038 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
5040 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
5041 << ObjectType << Base->getSourceRange();
5045 // C++ [expr.pseudo]p2:
5046 // [...] The cv-unqualified versions of the object type and of the type
5047 // designated by the pseudo-destructor-name shall be the same type.
5048 if (DestructedTypeInfo) {
5049 QualType DestructedType = DestructedTypeInfo->getType();
5050 SourceLocation DestructedTypeStart
5051 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
5052 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
5053 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
5054 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
5055 << ObjectType << DestructedType << Base->getSourceRange()
5056 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5058 // Recover by setting the destructed type to the object type.
5059 DestructedType = ObjectType;
5060 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5061 DestructedTypeStart);
5062 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5063 } else if (DestructedType.getObjCLifetime() !=
5064 ObjectType.getObjCLifetime()) {
5066 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
5067 // Okay: just pretend that the user provided the correctly-qualified
5070 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
5071 << ObjectType << DestructedType << Base->getSourceRange()
5072 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5075 // Recover by setting the destructed type to the object type.
5076 DestructedType = ObjectType;
5077 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5078 DestructedTypeStart);
5079 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5084 // C++ [expr.pseudo]p2:
5085 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5088 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
5090 // shall designate the same scalar type.
5091 if (ScopeTypeInfo) {
5092 QualType ScopeType = ScopeTypeInfo->getType();
5093 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
5094 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
5096 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
5097 diag::err_pseudo_dtor_type_mismatch)
5098 << ObjectType << ScopeType << Base->getSourceRange()
5099 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
5101 ScopeType = QualType();
5107 = new (Context) CXXPseudoDestructorExpr(Context, Base,
5108 OpKind == tok::arrow, OpLoc,
5109 SS.getWithLocInContext(Context),
5115 if (HasTrailingLParen)
5116 return Owned(Result);
5118 return DiagnoseDtorReference(Destructed.getLocation(), Result);
5121 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5122 SourceLocation OpLoc,
5123 tok::TokenKind OpKind,
5125 UnqualifiedId &FirstTypeName,
5126 SourceLocation CCLoc,
5127 SourceLocation TildeLoc,
5128 UnqualifiedId &SecondTypeName,
5129 bool HasTrailingLParen) {
5130 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5131 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5132 "Invalid first type name in pseudo-destructor");
5133 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5134 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5135 "Invalid second type name in pseudo-destructor");
5137 QualType ObjectType;
5138 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5141 // Compute the object type that we should use for name lookup purposes. Only
5142 // record types and dependent types matter.
5143 ParsedType ObjectTypePtrForLookup;
5145 if (ObjectType->isRecordType())
5146 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
5147 else if (ObjectType->isDependentType())
5148 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
5151 // Convert the name of the type being destructed (following the ~) into a
5152 // type (with source-location information).
5153 QualType DestructedType;
5154 TypeSourceInfo *DestructedTypeInfo = 0;
5155 PseudoDestructorTypeStorage Destructed;
5156 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5157 ParsedType T = getTypeName(*SecondTypeName.Identifier,
5158 SecondTypeName.StartLocation,
5159 S, &SS, true, false, ObjectTypePtrForLookup);
5161 ((SS.isSet() && !computeDeclContext(SS, false)) ||
5162 (!SS.isSet() && ObjectType->isDependentType()))) {
5163 // The name of the type being destroyed is a dependent name, and we
5164 // couldn't find anything useful in scope. Just store the identifier and
5165 // it's location, and we'll perform (qualified) name lookup again at
5166 // template instantiation time.
5167 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5168 SecondTypeName.StartLocation);
5170 Diag(SecondTypeName.StartLocation,
5171 diag::err_pseudo_dtor_destructor_non_type)
5172 << SecondTypeName.Identifier << ObjectType;
5173 if (isSFINAEContext())
5176 // Recover by assuming we had the right type all along.
5177 DestructedType = ObjectType;
5179 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
5181 // Resolve the template-id to a type.
5182 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
5183 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5184 TemplateId->NumArgs);
5185 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5186 TemplateId->TemplateKWLoc,
5187 TemplateId->Template,
5188 TemplateId->TemplateNameLoc,
5189 TemplateId->LAngleLoc,
5191 TemplateId->RAngleLoc);
5192 if (T.isInvalid() || !T.get()) {
5193 // Recover by assuming we had the right type all along.
5194 DestructedType = ObjectType;
5196 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
5199 // If we've performed some kind of recovery, (re-)build the type source
5201 if (!DestructedType.isNull()) {
5202 if (!DestructedTypeInfo)
5203 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
5204 SecondTypeName.StartLocation);
5205 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5208 // Convert the name of the scope type (the type prior to '::') into a type.
5209 TypeSourceInfo *ScopeTypeInfo = 0;
5211 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5212 FirstTypeName.Identifier) {
5213 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5214 ParsedType T = getTypeName(*FirstTypeName.Identifier,
5215 FirstTypeName.StartLocation,
5216 S, &SS, true, false, ObjectTypePtrForLookup);
5218 Diag(FirstTypeName.StartLocation,
5219 diag::err_pseudo_dtor_destructor_non_type)
5220 << FirstTypeName.Identifier << ObjectType;
5222 if (isSFINAEContext())
5225 // Just drop this type. It's unnecessary anyway.
5226 ScopeType = QualType();
5228 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
5230 // Resolve the template-id to a type.
5231 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
5232 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5233 TemplateId->NumArgs);
5234 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5235 TemplateId->TemplateKWLoc,
5236 TemplateId->Template,
5237 TemplateId->TemplateNameLoc,
5238 TemplateId->LAngleLoc,
5240 TemplateId->RAngleLoc);
5241 if (T.isInvalid() || !T.get()) {
5242 // Recover by dropping this type.
5243 ScopeType = QualType();
5245 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
5249 if (!ScopeType.isNull() && !ScopeTypeInfo)
5250 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5251 FirstTypeName.StartLocation);
5254 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
5255 ScopeTypeInfo, CCLoc, TildeLoc,
5256 Destructed, HasTrailingLParen);
5259 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5260 SourceLocation OpLoc,
5261 tok::TokenKind OpKind,
5262 SourceLocation TildeLoc,
5264 bool HasTrailingLParen) {
5265 QualType ObjectType;
5266 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5269 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5272 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5273 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5274 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5275 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5277 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5278 0, SourceLocation(), TildeLoc,
5279 Destructed, HasTrailingLParen);
5282 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
5283 CXXConversionDecl *Method,
5284 bool HadMultipleCandidates) {
5285 if (Method->getParent()->isLambda() &&
5286 Method->getConversionType()->isBlockPointerType()) {
5287 // This is a lambda coversion to block pointer; check if the argument
5290 CastExpr *CE = dyn_cast<CastExpr>(SubE);
5291 if (CE && CE->getCastKind() == CK_NoOp)
5292 SubE = CE->getSubExpr();
5293 SubE = SubE->IgnoreParens();
5294 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5295 SubE = BE->getSubExpr();
5296 if (isa<LambdaExpr>(SubE)) {
5297 // For the conversion to block pointer on a lambda expression, we
5298 // construct a special BlockLiteral instead; this doesn't really make
5299 // a difference in ARC, but outside of ARC the resulting block literal
5300 // follows the normal lifetime rules for block literals instead of being
5302 DiagnosticErrorTrap Trap(Diags);
5303 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5306 if (Exp.isInvalid())
5307 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5313 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5315 if (Exp.isInvalid())
5319 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
5320 SourceLocation(), Context.BoundMemberTy,
5321 VK_RValue, OK_Ordinary);
5322 if (HadMultipleCandidates)
5323 ME->setHadMultipleCandidates(true);
5325 QualType ResultType = Method->getResultType();
5326 ExprValueKind VK = Expr::getValueKindForType(ResultType);
5327 ResultType = ResultType.getNonLValueExprType(Context);
5329 MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
5330 CXXMemberCallExpr *CE =
5331 new (Context) CXXMemberCallExpr(Context, ME, MultiExprArg(), ResultType, VK,
5332 Exp.get()->getLocEnd());
5336 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5337 SourceLocation RParen) {
5338 CanThrowResult CanThrow = canThrow(Operand);
5339 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
5340 CanThrow, KeyLoc, RParen));
5343 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5344 Expr *Operand, SourceLocation RParen) {
5345 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
5348 static bool IsSpecialDiscardedValue(Expr *E) {
5349 // In C++11, discarded-value expressions of a certain form are special,
5350 // according to [expr]p10:
5351 // The lvalue-to-rvalue conversion (4.1) is applied only if the
5352 // expression is an lvalue of volatile-qualified type and it has
5353 // one of the following forms:
5354 E = E->IgnoreParens();
5356 // - id-expression (5.1.1),
5357 if (isa<DeclRefExpr>(E))
5360 // - subscripting (5.2.1),
5361 if (isa<ArraySubscriptExpr>(E))
5364 // - class member access (5.2.5),
5365 if (isa<MemberExpr>(E))
5368 // - indirection (5.3.1),
5369 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
5370 if (UO->getOpcode() == UO_Deref)
5373 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5374 // - pointer-to-member operation (5.5),
5375 if (BO->isPtrMemOp())
5378 // - comma expression (5.18) where the right operand is one of the above.
5379 if (BO->getOpcode() == BO_Comma)
5380 return IsSpecialDiscardedValue(BO->getRHS());
5383 // - conditional expression (5.16) where both the second and the third
5384 // operands are one of the above, or
5385 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
5386 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
5387 IsSpecialDiscardedValue(CO->getFalseExpr());
5388 // The related edge case of "*x ?: *x".
5389 if (BinaryConditionalOperator *BCO =
5390 dyn_cast<BinaryConditionalOperator>(E)) {
5391 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
5392 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
5393 IsSpecialDiscardedValue(BCO->getFalseExpr());
5396 // Objective-C++ extensions to the rule.
5397 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
5403 /// Perform the conversions required for an expression used in a
5404 /// context that ignores the result.
5405 ExprResult Sema::IgnoredValueConversions(Expr *E) {
5406 if (E->hasPlaceholderType()) {
5407 ExprResult result = CheckPlaceholderExpr(E);
5408 if (result.isInvalid()) return Owned(E);
5413 // [Except in specific positions,] an lvalue that does not have
5414 // array type is converted to the value stored in the
5415 // designated object (and is no longer an lvalue).
5416 if (E->isRValue()) {
5417 // In C, function designators (i.e. expressions of function type)
5418 // are r-values, but we still want to do function-to-pointer decay
5419 // on them. This is both technically correct and convenient for
5421 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
5422 return DefaultFunctionArrayConversion(E);
5427 if (getLangOpts().CPlusPlus) {
5428 // The C++11 standard defines the notion of a discarded-value expression;
5429 // normally, we don't need to do anything to handle it, but if it is a
5430 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
5432 if (getLangOpts().CPlusPlus0x && E->isGLValue() &&
5433 E->getType().isVolatileQualified() &&
5434 IsSpecialDiscardedValue(E)) {
5435 ExprResult Res = DefaultLvalueConversion(E);
5436 if (Res.isInvalid())
5443 // GCC seems to also exclude expressions of incomplete enum type.
5444 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5445 if (!T->getDecl()->isComplete()) {
5446 // FIXME: stupid workaround for a codegen bug!
5447 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5452 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5453 if (Res.isInvalid())
5457 if (!E->getType()->isVoidType())
5458 RequireCompleteType(E->getExprLoc(), E->getType(),
5459 diag::err_incomplete_type);
5463 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC) {
5464 ExprResult FullExpr = Owned(FE);
5466 if (!FullExpr.get())
5469 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
5472 // Top-level message sends default to 'id' when we're in a debugger.
5473 if (getLangOpts().DebuggerCastResultToId &&
5474 FullExpr.get()->getType() == Context.UnknownAnyTy &&
5475 isa<ObjCMessageExpr>(FullExpr.get())) {
5476 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5477 if (FullExpr.isInvalid())
5481 FullExpr = CheckPlaceholderExpr(FullExpr.take());
5482 if (FullExpr.isInvalid())
5485 FullExpr = IgnoredValueConversions(FullExpr.take());
5486 if (FullExpr.isInvalid())
5489 CheckImplicitConversions(FullExpr.get(), CC);
5490 return MaybeCreateExprWithCleanups(FullExpr);
5493 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
5494 if (!FullStmt) return StmtError();
5496 return MaybeCreateStmtWithCleanups(FullStmt);
5499 Sema::IfExistsResult
5500 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
5502 const DeclarationNameInfo &TargetNameInfo) {
5503 DeclarationName TargetName = TargetNameInfo.getName();
5505 return IER_DoesNotExist;
5507 // If the name itself is dependent, then the result is dependent.
5508 if (TargetName.isDependentName())
5509 return IER_Dependent;
5511 // Do the redeclaration lookup in the current scope.
5512 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
5513 Sema::NotForRedeclaration);
5514 LookupParsedName(R, S, &SS);
5515 R.suppressDiagnostics();
5517 switch (R.getResultKind()) {
5518 case LookupResult::Found:
5519 case LookupResult::FoundOverloaded:
5520 case LookupResult::FoundUnresolvedValue:
5521 case LookupResult::Ambiguous:
5524 case LookupResult::NotFound:
5525 return IER_DoesNotExist;
5527 case LookupResult::NotFoundInCurrentInstantiation:
5528 return IER_Dependent;
5531 llvm_unreachable("Invalid LookupResult Kind!");
5534 Sema::IfExistsResult
5535 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5536 bool IsIfExists, CXXScopeSpec &SS,
5537 UnqualifiedId &Name) {
5538 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5540 // Check for unexpanded parameter packs.
5541 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5542 collectUnexpandedParameterPacks(SS, Unexpanded);
5543 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
5544 if (!Unexpanded.empty()) {
5545 DiagnoseUnexpandedParameterPacks(KeywordLoc,
5546 IsIfExists? UPPC_IfExists
5552 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);