implement a nice new optimization: CodeGenTypes::UpdateCompletedType
[clang/stm8.git] / lib / Sema / SemaExprCXX.cpp
blob7ee9c1bec2041af5411d029ad9ab65e2e455f9ce
1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for C++ expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/DeclSpec.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/ParsedTemplate.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Sema/Scope.h"
21 #include "clang/Sema/TemplateDeduction.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/ErrorHandling.h"
33 using namespace clang;
34 using namespace sema;
36 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
37 IdentifierInfo &II,
38 SourceLocation NameLoc,
39 Scope *S, CXXScopeSpec &SS,
40 ParsedType ObjectTypePtr,
41 bool EnteringContext) {
42 // Determine where to perform name lookup.
44 // FIXME: This area of the standard is very messy, and the current
45 // wording is rather unclear about which scopes we search for the
46 // destructor name; see core issues 399 and 555. Issue 399 in
47 // particular shows where the current description of destructor name
48 // lookup is completely out of line with existing practice, e.g.,
49 // this appears to be ill-formed:
51 // namespace N {
52 // template <typename T> struct S {
53 // ~S();
54 // };
55 // }
57 // void f(N::S<int>* s) {
58 // s->N::S<int>::~S();
59 // }
61 // See also PR6358 and PR6359.
62 // For this reason, we're currently only doing the C++03 version of this
63 // code; the C++0x version has to wait until we get a proper spec.
64 QualType SearchType;
65 DeclContext *LookupCtx = 0;
66 bool isDependent = false;
67 bool LookInScope = false;
69 // If we have an object type, it's because we are in a
70 // pseudo-destructor-expression or a member access expression, and
71 // we know what type we're looking for.
72 if (ObjectTypePtr)
73 SearchType = GetTypeFromParser(ObjectTypePtr);
75 if (SS.isSet()) {
76 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
78 bool AlreadySearched = false;
79 bool LookAtPrefix = true;
80 // C++ [basic.lookup.qual]p6:
81 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
82 // the type-names are looked up as types in the scope designated by the
83 // nested-name-specifier. In a qualified-id of the form:
85 // ::[opt] nested-name-specifier ~ class-name
87 // where the nested-name-specifier designates a namespace scope, and in
88 // a qualified-id of the form:
90 // ::opt nested-name-specifier class-name :: ~ class-name
92 // the class-names are looked up as types in the scope designated by
93 // the nested-name-specifier.
95 // Here, we check the first case (completely) and determine whether the
96 // code below is permitted to look at the prefix of the
97 // nested-name-specifier.
98 DeclContext *DC = computeDeclContext(SS, EnteringContext);
99 if (DC && DC->isFileContext()) {
100 AlreadySearched = true;
101 LookupCtx = DC;
102 isDependent = false;
103 } else if (DC && isa<CXXRecordDecl>(DC))
104 LookAtPrefix = false;
106 // The second case from the C++03 rules quoted further above.
107 NestedNameSpecifier *Prefix = 0;
108 if (AlreadySearched) {
109 // Nothing left to do.
110 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
111 CXXScopeSpec PrefixSS;
112 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
113 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
114 isDependent = isDependentScopeSpecifier(PrefixSS);
115 } else if (ObjectTypePtr) {
116 LookupCtx = computeDeclContext(SearchType);
117 isDependent = SearchType->isDependentType();
118 } else {
119 LookupCtx = computeDeclContext(SS, EnteringContext);
120 isDependent = LookupCtx && LookupCtx->isDependentContext();
123 LookInScope = false;
124 } else if (ObjectTypePtr) {
125 // C++ [basic.lookup.classref]p3:
126 // If the unqualified-id is ~type-name, the type-name is looked up
127 // in the context of the entire postfix-expression. If the type T
128 // of the object expression is of a class type C, the type-name is
129 // also looked up in the scope of class C. At least one of the
130 // lookups shall find a name that refers to (possibly
131 // cv-qualified) T.
132 LookupCtx = computeDeclContext(SearchType);
133 isDependent = SearchType->isDependentType();
134 assert((isDependent || !SearchType->isIncompleteType()) &&
135 "Caller should have completed object type");
137 LookInScope = true;
138 } else {
139 // Perform lookup into the current scope (only).
140 LookInScope = true;
143 TypeDecl *NonMatchingTypeDecl = 0;
144 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
145 for (unsigned Step = 0; Step != 2; ++Step) {
146 // Look for the name first in the computed lookup context (if we
147 // have one) and, if that fails to find a match, in the scope (if
148 // we're allowed to look there).
149 Found.clear();
150 if (Step == 0 && LookupCtx)
151 LookupQualifiedName(Found, LookupCtx);
152 else if (Step == 1 && LookInScope && S)
153 LookupName(Found, S);
154 else
155 continue;
157 // FIXME: Should we be suppressing ambiguities here?
158 if (Found.isAmbiguous())
159 return ParsedType();
161 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
162 QualType T = Context.getTypeDeclType(Type);
164 if (SearchType.isNull() || SearchType->isDependentType() ||
165 Context.hasSameUnqualifiedType(T, SearchType)) {
166 // We found our type!
168 return ParsedType::make(T);
171 if (!SearchType.isNull())
172 NonMatchingTypeDecl = Type;
175 // If the name that we found is a class template name, and it is
176 // the same name as the template name in the last part of the
177 // nested-name-specifier (if present) or the object type, then
178 // this is the destructor for that class.
179 // FIXME: This is a workaround until we get real drafting for core
180 // issue 399, for which there isn't even an obvious direction.
181 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
182 QualType MemberOfType;
183 if (SS.isSet()) {
184 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
185 // Figure out the type of the context, if it has one.
186 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
187 MemberOfType = Context.getTypeDeclType(Record);
190 if (MemberOfType.isNull())
191 MemberOfType = SearchType;
193 if (MemberOfType.isNull())
194 continue;
196 // We're referring into a class template specialization. If the
197 // class template we found is the same as the template being
198 // specialized, we found what we are looking for.
199 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
200 if (ClassTemplateSpecializationDecl *Spec
201 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
202 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
203 Template->getCanonicalDecl())
204 return ParsedType::make(MemberOfType);
207 continue;
210 // We're referring to an unresolved class template
211 // specialization. Determine whether we class template we found
212 // is the same as the template being specialized or, if we don't
213 // know which template is being specialized, that it at least
214 // has the same name.
215 if (const TemplateSpecializationType *SpecType
216 = MemberOfType->getAs<TemplateSpecializationType>()) {
217 TemplateName SpecName = SpecType->getTemplateName();
219 // The class template we found is the same template being
220 // specialized.
221 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
222 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
223 return ParsedType::make(MemberOfType);
225 continue;
228 // The class template we found has the same name as the
229 // (dependent) template name being specialized.
230 if (DependentTemplateName *DepTemplate
231 = SpecName.getAsDependentTemplateName()) {
232 if (DepTemplate->isIdentifier() &&
233 DepTemplate->getIdentifier() == Template->getIdentifier())
234 return ParsedType::make(MemberOfType);
236 continue;
242 if (isDependent) {
243 // We didn't find our type, but that's okay: it's dependent
244 // anyway.
246 // FIXME: What if we have no nested-name-specifier?
247 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
248 SS.getWithLocInContext(Context),
249 II, NameLoc);
250 return ParsedType::make(T);
253 if (NonMatchingTypeDecl) {
254 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
255 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
256 << T << SearchType;
257 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
258 << T;
259 } else if (ObjectTypePtr)
260 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
261 << &II;
262 else
263 Diag(NameLoc, diag::err_destructor_class_name);
265 return ParsedType();
268 /// \brief Build a C++ typeid expression with a type operand.
269 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
270 SourceLocation TypeidLoc,
271 TypeSourceInfo *Operand,
272 SourceLocation RParenLoc) {
273 // C++ [expr.typeid]p4:
274 // The top-level cv-qualifiers of the lvalue expression or the type-id
275 // that is the operand of typeid are always ignored.
276 // If the type of the type-id is a class type or a reference to a class
277 // type, the class shall be completely-defined.
278 Qualifiers Quals;
279 QualType T
280 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
281 Quals);
282 if (T->getAs<RecordType>() &&
283 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
284 return ExprError();
286 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
287 Operand,
288 SourceRange(TypeidLoc, RParenLoc)));
291 /// \brief Build a C++ typeid expression with an expression operand.
292 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
293 SourceLocation TypeidLoc,
294 Expr *E,
295 SourceLocation RParenLoc) {
296 bool isUnevaluatedOperand = true;
297 if (E && !E->isTypeDependent()) {
298 QualType T = E->getType();
299 if (const RecordType *RecordT = T->getAs<RecordType>()) {
300 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
301 // C++ [expr.typeid]p3:
302 // [...] If the type of the expression is a class type, the class
303 // shall be completely-defined.
304 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
305 return ExprError();
307 // C++ [expr.typeid]p3:
308 // When typeid is applied to an expression other than an glvalue of a
309 // polymorphic class type [...] [the] expression is an unevaluated
310 // operand. [...]
311 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
312 isUnevaluatedOperand = false;
314 // We require a vtable to query the type at run time.
315 MarkVTableUsed(TypeidLoc, RecordD);
319 // C++ [expr.typeid]p4:
320 // [...] If the type of the type-id is a reference to a possibly
321 // cv-qualified type, the result of the typeid expression refers to a
322 // std::type_info object representing the cv-unqualified referenced
323 // type.
324 Qualifiers Quals;
325 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
326 if (!Context.hasSameType(T, UnqualT)) {
327 T = UnqualT;
328 E = ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)).take();
332 // If this is an unevaluated operand, clear out the set of
333 // declaration references we have been computing and eliminate any
334 // temporaries introduced in its computation.
335 if (isUnevaluatedOperand)
336 ExprEvalContexts.back().Context = Unevaluated;
338 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
340 SourceRange(TypeidLoc, RParenLoc)));
343 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
344 ExprResult
345 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
346 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
347 // Find the std::type_info type.
348 if (!getStdNamespace())
349 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
351 if (!CXXTypeInfoDecl) {
352 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
353 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
354 LookupQualifiedName(R, getStdNamespace());
355 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
356 if (!CXXTypeInfoDecl)
357 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
360 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
362 if (isType) {
363 // The operand is a type; handle it as such.
364 TypeSourceInfo *TInfo = 0;
365 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
366 &TInfo);
367 if (T.isNull())
368 return ExprError();
370 if (!TInfo)
371 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
373 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
376 // The operand is an expression.
377 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
380 /// Retrieve the UuidAttr associated with QT.
381 static UuidAttr *GetUuidAttrOfType(QualType QT) {
382 // Optionally remove one level of pointer, reference or array indirection.
383 const Type *Ty = QT.getTypePtr();;
384 if (QT->isPointerType() || QT->isReferenceType())
385 Ty = QT->getPointeeType().getTypePtr();
386 else if (QT->isArrayType())
387 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
389 // Loop all record redeclaration looking for an uuid attribute.
390 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
391 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
392 E = RD->redecls_end(); I != E; ++I) {
393 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
394 return Uuid;
397 return 0;
400 /// \brief Build a Microsoft __uuidof expression with a type operand.
401 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
402 SourceLocation TypeidLoc,
403 TypeSourceInfo *Operand,
404 SourceLocation RParenLoc) {
405 if (!Operand->getType()->isDependentType()) {
406 if (!GetUuidAttrOfType(Operand->getType()))
407 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
410 // FIXME: add __uuidof semantic analysis for type operand.
411 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
412 Operand,
413 SourceRange(TypeidLoc, RParenLoc)));
416 /// \brief Build a Microsoft __uuidof expression with an expression operand.
417 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
418 SourceLocation TypeidLoc,
419 Expr *E,
420 SourceLocation RParenLoc) {
421 if (!E->getType()->isDependentType()) {
422 if (!GetUuidAttrOfType(E->getType()) &&
423 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
424 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
426 // FIXME: add __uuidof semantic analysis for type operand.
427 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
429 SourceRange(TypeidLoc, RParenLoc)));
432 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
433 ExprResult
434 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
435 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
436 // If MSVCGuidDecl has not been cached, do the lookup.
437 if (!MSVCGuidDecl) {
438 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
439 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
440 LookupQualifiedName(R, Context.getTranslationUnitDecl());
441 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
442 if (!MSVCGuidDecl)
443 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
446 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
448 if (isType) {
449 // The operand is a type; handle it as such.
450 TypeSourceInfo *TInfo = 0;
451 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
452 &TInfo);
453 if (T.isNull())
454 return ExprError();
456 if (!TInfo)
457 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
459 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
462 // The operand is an expression.
463 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
466 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
467 ExprResult
468 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
469 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
470 "Unknown C++ Boolean value!");
471 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
472 Context.BoolTy, OpLoc));
475 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
476 ExprResult
477 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
478 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
481 /// ActOnCXXThrow - Parse throw expressions.
482 ExprResult
483 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
484 bool IsThrownVarInScope = false;
485 if (Ex) {
486 // C++0x [class.copymove]p31:
487 // When certain criteria are met, an implementation is allowed to omit the
488 // copy/move construction of a class object [...]
490 // - in a throw-expression, when the operand is the name of a
491 // non-volatile automatic object (other than a function or catch-
492 // clause parameter) whose scope does not extend beyond the end of the
493 // innermost enclosing try-block (if there is one), the copy/move
494 // operation from the operand to the exception object (15.1) can be
495 // omitted by constructing the automatic object directly into the
496 // exception object
497 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
498 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
499 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
500 for( ; S; S = S->getParent()) {
501 if (S->isDeclScope(Var)) {
502 IsThrownVarInScope = true;
503 break;
506 if (S->getFlags() &
507 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
508 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
509 Scope::TryScope))
510 break;
516 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
519 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
520 bool IsThrownVarInScope) {
521 // Don't report an error if 'throw' is used in system headers.
522 if (!getLangOptions().CXXExceptions &&
523 !getSourceManager().isInSystemHeader(OpLoc))
524 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
526 if (Ex && !Ex->isTypeDependent()) {
527 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
528 if (ExRes.isInvalid())
529 return ExprError();
530 Ex = ExRes.take();
533 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
534 IsThrownVarInScope));
537 /// CheckCXXThrowOperand - Validate the operand of a throw.
538 ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
539 bool IsThrownVarInScope) {
540 // C++ [except.throw]p3:
541 // A throw-expression initializes a temporary object, called the exception
542 // object, the type of which is determined by removing any top-level
543 // cv-qualifiers from the static type of the operand of throw and adjusting
544 // the type from "array of T" or "function returning T" to "pointer to T"
545 // or "pointer to function returning T", [...]
546 if (E->getType().hasQualifiers())
547 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
548 CastCategory(E)).take();
550 ExprResult Res = DefaultFunctionArrayConversion(E);
551 if (Res.isInvalid())
552 return ExprError();
553 E = Res.take();
555 // If the type of the exception would be an incomplete type or a pointer
556 // to an incomplete type other than (cv) void the program is ill-formed.
557 QualType Ty = E->getType();
558 bool isPointer = false;
559 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
560 Ty = Ptr->getPointeeType();
561 isPointer = true;
563 if (!isPointer || !Ty->isVoidType()) {
564 if (RequireCompleteType(ThrowLoc, Ty,
565 PDiag(isPointer ? diag::err_throw_incomplete_ptr
566 : diag::err_throw_incomplete)
567 << E->getSourceRange()))
568 return ExprError();
570 if (RequireNonAbstractType(ThrowLoc, E->getType(),
571 PDiag(diag::err_throw_abstract_type)
572 << E->getSourceRange()))
573 return ExprError();
576 // Initialize the exception result. This implicitly weeds out
577 // abstract types or types with inaccessible copy constructors.
579 // C++0x [class.copymove]p31:
580 // When certain criteria are met, an implementation is allowed to omit the
581 // copy/move construction of a class object [...]
583 // - in a throw-expression, when the operand is the name of a
584 // non-volatile automatic object (other than a function or catch-clause
585 // parameter) whose scope does not extend beyond the end of the
586 // innermost enclosing try-block (if there is one), the copy/move
587 // operation from the operand to the exception object (15.1) can be
588 // omitted by constructing the automatic object directly into the
589 // exception object
590 const VarDecl *NRVOVariable = 0;
591 if (IsThrownVarInScope)
592 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
594 InitializedEntity Entity =
595 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
596 /*NRVO=*/NRVOVariable != 0);
597 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
598 QualType(), E,
599 IsThrownVarInScope);
600 if (Res.isInvalid())
601 return ExprError();
602 E = Res.take();
604 // If the exception has class type, we need additional handling.
605 const RecordType *RecordTy = Ty->getAs<RecordType>();
606 if (!RecordTy)
607 return Owned(E);
608 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
610 // If we are throwing a polymorphic class type or pointer thereof,
611 // exception handling will make use of the vtable.
612 MarkVTableUsed(ThrowLoc, RD);
614 // If a pointer is thrown, the referenced object will not be destroyed.
615 if (isPointer)
616 return Owned(E);
618 // If the class has a non-trivial destructor, we must be able to call it.
619 if (RD->hasTrivialDestructor())
620 return Owned(E);
622 CXXDestructorDecl *Destructor
623 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
624 if (!Destructor)
625 return Owned(E);
627 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
628 CheckDestructorAccess(E->getExprLoc(), Destructor,
629 PDiag(diag::err_access_dtor_exception) << Ty);
630 return Owned(E);
633 QualType Sema::getAndCaptureCurrentThisType() {
634 // Ignore block scopes: we can capture through them.
635 // Ignore nested enum scopes: we'll diagnose non-constant expressions
636 // where they're invalid, and other uses are legitimate.
637 // Don't ignore nested class scopes: you can't use 'this' in a local class.
638 DeclContext *DC = CurContext;
639 unsigned NumBlocks = 0;
640 while (true) {
641 if (isa<BlockDecl>(DC)) {
642 DC = cast<BlockDecl>(DC)->getDeclContext();
643 ++NumBlocks;
644 } else if (isa<EnumDecl>(DC))
645 DC = cast<EnumDecl>(DC)->getDeclContext();
646 else break;
649 QualType ThisTy;
650 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
651 if (method && method->isInstance())
652 ThisTy = method->getThisType(Context);
653 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
654 // C++0x [expr.prim]p4:
655 // Otherwise, if a member-declarator declares a non-static data member
656 // of a class X, the expression this is a prvalue of type "pointer to X"
657 // within the optional brace-or-equal-initializer.
658 Scope *S = getScopeForContext(DC);
659 if (!S || S->getFlags() & Scope::ThisScope)
660 ThisTy = Context.getPointerType(Context.getRecordType(RD));
663 // Mark that we're closing on 'this' in all the block scopes we ignored.
664 if (!ThisTy.isNull())
665 for (unsigned idx = FunctionScopes.size() - 1;
666 NumBlocks; --idx, --NumBlocks)
667 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
669 return ThisTy;
672 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
673 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
674 /// is a non-lvalue expression whose value is the address of the object for
675 /// which the function is called.
677 QualType ThisTy = getAndCaptureCurrentThisType();
678 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
680 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
683 ExprResult
684 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
685 SourceLocation LParenLoc,
686 MultiExprArg exprs,
687 SourceLocation RParenLoc) {
688 if (!TypeRep)
689 return ExprError();
691 TypeSourceInfo *TInfo;
692 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
693 if (!TInfo)
694 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
696 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
699 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
700 /// Can be interpreted either as function-style casting ("int(x)")
701 /// or class type construction ("ClassType(x,y,z)")
702 /// or creation of a value-initialized type ("int()").
703 ExprResult
704 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
705 SourceLocation LParenLoc,
706 MultiExprArg exprs,
707 SourceLocation RParenLoc) {
708 QualType Ty = TInfo->getType();
709 unsigned NumExprs = exprs.size();
710 Expr **Exprs = (Expr**)exprs.get();
711 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
712 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
714 if (Ty->isDependentType() ||
715 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
716 exprs.release();
718 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
719 LParenLoc,
720 Exprs, NumExprs,
721 RParenLoc));
724 if (Ty->isArrayType())
725 return ExprError(Diag(TyBeginLoc,
726 diag::err_value_init_for_array_type) << FullRange);
727 if (!Ty->isVoidType() &&
728 RequireCompleteType(TyBeginLoc, Ty,
729 PDiag(diag::err_invalid_incomplete_type_use)
730 << FullRange))
731 return ExprError();
733 if (RequireNonAbstractType(TyBeginLoc, Ty,
734 diag::err_allocation_of_abstract_type))
735 return ExprError();
738 // C++ [expr.type.conv]p1:
739 // If the expression list is a single expression, the type conversion
740 // expression is equivalent (in definedness, and if defined in meaning) to the
741 // corresponding cast expression.
743 if (NumExprs == 1) {
744 CastKind Kind = CK_Invalid;
745 ExprValueKind VK = VK_RValue;
746 CXXCastPath BasePath;
747 ExprResult CastExpr =
748 CheckCastTypes(TInfo->getTypeLoc().getBeginLoc(),
749 TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
750 Kind, VK, BasePath,
751 /*FunctionalStyle=*/true);
752 if (CastExpr.isInvalid())
753 return ExprError();
754 Exprs[0] = CastExpr.take();
756 exprs.release();
758 return Owned(CXXFunctionalCastExpr::Create(Context,
759 Ty.getNonLValueExprType(Context),
760 VK, TInfo, TyBeginLoc, Kind,
761 Exprs[0], &BasePath,
762 RParenLoc));
765 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
766 InitializationKind Kind
767 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
768 LParenLoc, RParenLoc)
769 : InitializationKind::CreateValue(TyBeginLoc,
770 LParenLoc, RParenLoc);
771 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
772 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
774 // FIXME: Improve AST representation?
775 return move(Result);
778 /// doesUsualArrayDeleteWantSize - Answers whether the usual
779 /// operator delete[] for the given type has a size_t parameter.
780 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
781 QualType allocType) {
782 const RecordType *record =
783 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
784 if (!record) return false;
786 // Try to find an operator delete[] in class scope.
788 DeclarationName deleteName =
789 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
790 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
791 S.LookupQualifiedName(ops, record->getDecl());
793 // We're just doing this for information.
794 ops.suppressDiagnostics();
796 // Very likely: there's no operator delete[].
797 if (ops.empty()) return false;
799 // If it's ambiguous, it should be illegal to call operator delete[]
800 // on this thing, so it doesn't matter if we allocate extra space or not.
801 if (ops.isAmbiguous()) return false;
803 LookupResult::Filter filter = ops.makeFilter();
804 while (filter.hasNext()) {
805 NamedDecl *del = filter.next()->getUnderlyingDecl();
807 // C++0x [basic.stc.dynamic.deallocation]p2:
808 // A template instance is never a usual deallocation function,
809 // regardless of its signature.
810 if (isa<FunctionTemplateDecl>(del)) {
811 filter.erase();
812 continue;
815 // C++0x [basic.stc.dynamic.deallocation]p2:
816 // If class T does not declare [an operator delete[] with one
817 // parameter] but does declare a member deallocation function
818 // named operator delete[] with exactly two parameters, the
819 // second of which has type std::size_t, then this function
820 // is a usual deallocation function.
821 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
822 filter.erase();
823 continue;
826 filter.done();
828 if (!ops.isSingleResult()) return false;
830 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
831 return (del->getNumParams() == 2);
834 /// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
835 /// @code new (memory) int[size][4] @endcode
836 /// or
837 /// @code ::new Foo(23, "hello") @endcode
838 /// For the interpretation of this heap of arguments, consult the base version.
839 ExprResult
840 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
841 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
842 SourceLocation PlacementRParen, SourceRange TypeIdParens,
843 Declarator &D, SourceLocation ConstructorLParen,
844 MultiExprArg ConstructorArgs,
845 SourceLocation ConstructorRParen) {
846 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
848 Expr *ArraySize = 0;
849 // If the specified type is an array, unwrap it and save the expression.
850 if (D.getNumTypeObjects() > 0 &&
851 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
852 DeclaratorChunk &Chunk = D.getTypeObject(0);
853 if (TypeContainsAuto)
854 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
855 << D.getSourceRange());
856 if (Chunk.Arr.hasStatic)
857 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
858 << D.getSourceRange());
859 if (!Chunk.Arr.NumElts)
860 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
861 << D.getSourceRange());
863 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
864 D.DropFirstTypeObject();
867 // Every dimension shall be of constant size.
868 if (ArraySize) {
869 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
870 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
871 break;
873 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
874 if (Expr *NumElts = (Expr *)Array.NumElts) {
875 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
876 !NumElts->isIntegerConstantExpr(Context)) {
877 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
878 << NumElts->getSourceRange();
879 return ExprError();
885 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
886 QualType AllocType = TInfo->getType();
887 if (D.isInvalidType())
888 return ExprError();
890 return BuildCXXNew(StartLoc, UseGlobal,
891 PlacementLParen,
892 move(PlacementArgs),
893 PlacementRParen,
894 TypeIdParens,
895 AllocType,
896 TInfo,
897 ArraySize,
898 ConstructorLParen,
899 move(ConstructorArgs),
900 ConstructorRParen,
901 TypeContainsAuto);
904 ExprResult
905 Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
906 SourceLocation PlacementLParen,
907 MultiExprArg PlacementArgs,
908 SourceLocation PlacementRParen,
909 SourceRange TypeIdParens,
910 QualType AllocType,
911 TypeSourceInfo *AllocTypeInfo,
912 Expr *ArraySize,
913 SourceLocation ConstructorLParen,
914 MultiExprArg ConstructorArgs,
915 SourceLocation ConstructorRParen,
916 bool TypeMayContainAuto) {
917 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
919 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
920 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
921 if (ConstructorArgs.size() == 0)
922 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
923 << AllocType << TypeRange);
924 if (ConstructorArgs.size() != 1) {
925 Expr *FirstBad = ConstructorArgs.get()[1];
926 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
927 diag::err_auto_new_ctor_multiple_expressions)
928 << AllocType << TypeRange);
930 TypeSourceInfo *DeducedType = 0;
931 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
932 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
933 << AllocType
934 << ConstructorArgs.get()[0]->getType()
935 << TypeRange
936 << ConstructorArgs.get()[0]->getSourceRange());
937 if (!DeducedType)
938 return ExprError();
940 AllocTypeInfo = DeducedType;
941 AllocType = AllocTypeInfo->getType();
944 // Per C++0x [expr.new]p5, the type being constructed may be a
945 // typedef of an array type.
946 if (!ArraySize) {
947 if (const ConstantArrayType *Array
948 = Context.getAsConstantArrayType(AllocType)) {
949 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
950 Context.getSizeType(),
951 TypeRange.getEnd());
952 AllocType = Array->getElementType();
956 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
957 return ExprError();
959 // In ARC, infer 'retaining' for the allocated
960 if (getLangOptions().ObjCAutoRefCount &&
961 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
962 AllocType->isObjCLifetimeType()) {
963 AllocType = Context.getLifetimeQualifiedType(AllocType,
964 AllocType->getObjCARCImplicitLifetime());
967 QualType ResultType = Context.getPointerType(AllocType);
969 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
970 // or enumeration type with a non-negative value."
971 if (ArraySize && !ArraySize->isTypeDependent()) {
973 QualType SizeType = ArraySize->getType();
975 ExprResult ConvertedSize
976 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
977 PDiag(diag::err_array_size_not_integral),
978 PDiag(diag::err_array_size_incomplete_type)
979 << ArraySize->getSourceRange(),
980 PDiag(diag::err_array_size_explicit_conversion),
981 PDiag(diag::note_array_size_conversion),
982 PDiag(diag::err_array_size_ambiguous_conversion),
983 PDiag(diag::note_array_size_conversion),
984 PDiag(getLangOptions().CPlusPlus0x? 0
985 : diag::ext_array_size_conversion));
986 if (ConvertedSize.isInvalid())
987 return ExprError();
989 ArraySize = ConvertedSize.take();
990 SizeType = ArraySize->getType();
991 if (!SizeType->isIntegralOrUnscopedEnumerationType())
992 return ExprError();
994 // Let's see if this is a constant < 0. If so, we reject it out of hand.
995 // We don't care about special rules, so we tell the machinery it's not
996 // evaluated - it gives us a result in more cases.
997 if (!ArraySize->isValueDependent()) {
998 llvm::APSInt Value;
999 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
1000 if (Value < llvm::APSInt(
1001 llvm::APInt::getNullValue(Value.getBitWidth()),
1002 Value.isUnsigned()))
1003 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
1004 diag::err_typecheck_negative_array_size)
1005 << ArraySize->getSourceRange());
1007 if (!AllocType->isDependentType()) {
1008 unsigned ActiveSizeBits
1009 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1010 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1011 Diag(ArraySize->getSourceRange().getBegin(),
1012 diag::err_array_too_large)
1013 << Value.toString(10)
1014 << ArraySize->getSourceRange();
1015 return ExprError();
1018 } else if (TypeIdParens.isValid()) {
1019 // Can't have dynamic array size when the type-id is in parentheses.
1020 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1021 << ArraySize->getSourceRange()
1022 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1023 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1025 TypeIdParens = SourceRange();
1029 // ARC: warn about ABI issues.
1030 if (getLangOptions().ObjCAutoRefCount) {
1031 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1032 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1033 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1034 << 0 << BaseAllocType;
1037 // Note that we do *not* convert the argument in any way. It can
1038 // be signed, larger than size_t, whatever.
1041 FunctionDecl *OperatorNew = 0;
1042 FunctionDecl *OperatorDelete = 0;
1043 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1044 unsigned NumPlaceArgs = PlacementArgs.size();
1046 if (!AllocType->isDependentType() &&
1047 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1048 FindAllocationFunctions(StartLoc,
1049 SourceRange(PlacementLParen, PlacementRParen),
1050 UseGlobal, AllocType, ArraySize, PlaceArgs,
1051 NumPlaceArgs, OperatorNew, OperatorDelete))
1052 return ExprError();
1054 // If this is an array allocation, compute whether the usual array
1055 // deallocation function for the type has a size_t parameter.
1056 bool UsualArrayDeleteWantsSize = false;
1057 if (ArraySize && !AllocType->isDependentType())
1058 UsualArrayDeleteWantsSize
1059 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1061 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
1062 if (OperatorNew) {
1063 // Add default arguments, if any.
1064 const FunctionProtoType *Proto =
1065 OperatorNew->getType()->getAs<FunctionProtoType>();
1066 VariadicCallType CallType =
1067 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
1069 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
1070 Proto, 1, PlaceArgs, NumPlaceArgs,
1071 AllPlaceArgs, CallType))
1072 return ExprError();
1074 NumPlaceArgs = AllPlaceArgs.size();
1075 if (NumPlaceArgs > 0)
1076 PlaceArgs = &AllPlaceArgs[0];
1079 bool Init = ConstructorLParen.isValid();
1080 // --- Choosing a constructor ---
1081 CXXConstructorDecl *Constructor = 0;
1082 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1083 unsigned NumConsArgs = ConstructorArgs.size();
1084 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
1086 // Array 'new' can't have any initializers.
1087 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
1088 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1089 ConsArgs[NumConsArgs - 1]->getLocEnd());
1091 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1092 return ExprError();
1095 if (!AllocType->isDependentType() &&
1096 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1097 // C++0x [expr.new]p15:
1098 // A new-expression that creates an object of type T initializes that
1099 // object as follows:
1100 InitializationKind Kind
1101 // - If the new-initializer is omitted, the object is default-
1102 // initialized (8.5); if no initialization is performed,
1103 // the object has indeterminate value
1104 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
1105 // - Otherwise, the new-initializer is interpreted according to the
1106 // initialization rules of 8.5 for direct-initialization.
1107 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1108 ConstructorLParen,
1109 ConstructorRParen);
1111 InitializedEntity Entity
1112 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1113 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
1114 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1115 move(ConstructorArgs));
1116 if (FullInit.isInvalid())
1117 return ExprError();
1119 // FullInit is our initializer; walk through it to determine if it's a
1120 // constructor call, which CXXNewExpr handles directly.
1121 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1122 if (CXXBindTemporaryExpr *Binder
1123 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1124 FullInitExpr = Binder->getSubExpr();
1125 if (CXXConstructExpr *Construct
1126 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1127 Constructor = Construct->getConstructor();
1128 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1129 AEnd = Construct->arg_end();
1130 A != AEnd; ++A)
1131 ConvertedConstructorArgs.push_back(*A);
1132 } else {
1133 // Take the converted initializer.
1134 ConvertedConstructorArgs.push_back(FullInit.release());
1136 } else {
1137 // No initialization required.
1140 // Take the converted arguments and use them for the new expression.
1141 NumConsArgs = ConvertedConstructorArgs.size();
1142 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
1145 // Mark the new and delete operators as referenced.
1146 if (OperatorNew)
1147 MarkDeclarationReferenced(StartLoc, OperatorNew);
1148 if (OperatorDelete)
1149 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1151 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
1153 PlacementArgs.release();
1154 ConstructorArgs.release();
1156 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1157 PlaceArgs, NumPlaceArgs, TypeIdParens,
1158 ArraySize, Constructor, Init,
1159 ConsArgs, NumConsArgs, OperatorDelete,
1160 UsualArrayDeleteWantsSize,
1161 ResultType, AllocTypeInfo,
1162 StartLoc,
1163 Init ? ConstructorRParen :
1164 TypeRange.getEnd(),
1165 ConstructorLParen, ConstructorRParen));
1168 /// CheckAllocatedType - Checks that a type is suitable as the allocated type
1169 /// in a new-expression.
1170 /// dimension off and stores the size expression in ArraySize.
1171 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1172 SourceRange R) {
1173 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1174 // abstract class type or array thereof.
1175 if (AllocType->isFunctionType())
1176 return Diag(Loc, diag::err_bad_new_type)
1177 << AllocType << 0 << R;
1178 else if (AllocType->isReferenceType())
1179 return Diag(Loc, diag::err_bad_new_type)
1180 << AllocType << 1 << R;
1181 else if (!AllocType->isDependentType() &&
1182 RequireCompleteType(Loc, AllocType,
1183 PDiag(diag::err_new_incomplete_type)
1184 << R))
1185 return true;
1186 else if (RequireNonAbstractType(Loc, AllocType,
1187 diag::err_allocation_of_abstract_type))
1188 return true;
1189 else if (AllocType->isVariablyModifiedType())
1190 return Diag(Loc, diag::err_variably_modified_new_type)
1191 << AllocType;
1192 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1193 return Diag(Loc, diag::err_address_space_qualified_new)
1194 << AllocType.getUnqualifiedType() << AddressSpace;
1195 else if (getLangOptions().ObjCAutoRefCount) {
1196 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1197 QualType BaseAllocType = Context.getBaseElementType(AT);
1198 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1199 BaseAllocType->isObjCLifetimeType())
1200 return Diag(Loc, diag::err_arc_new_array_without_ownership)
1201 << BaseAllocType;
1205 return false;
1208 /// \brief Determine whether the given function is a non-placement
1209 /// deallocation function.
1210 static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1211 if (FD->isInvalidDecl())
1212 return false;
1214 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1215 return Method->isUsualDeallocationFunction();
1217 return ((FD->getOverloadedOperator() == OO_Delete ||
1218 FD->getOverloadedOperator() == OO_Array_Delete) &&
1219 FD->getNumParams() == 1);
1222 /// FindAllocationFunctions - Finds the overloads of operator new and delete
1223 /// that are appropriate for the allocation.
1224 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1225 bool UseGlobal, QualType AllocType,
1226 bool IsArray, Expr **PlaceArgs,
1227 unsigned NumPlaceArgs,
1228 FunctionDecl *&OperatorNew,
1229 FunctionDecl *&OperatorDelete) {
1230 // --- Choosing an allocation function ---
1231 // C++ 5.3.4p8 - 14 & 18
1232 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1233 // in the scope of the allocated class.
1234 // 2) If an array size is given, look for operator new[], else look for
1235 // operator new.
1236 // 3) The first argument is always size_t. Append the arguments from the
1237 // placement form.
1239 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1240 // We don't care about the actual value of this argument.
1241 // FIXME: Should the Sema create the expression and embed it in the syntax
1242 // tree? Or should the consumer just recalculate the value?
1243 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1244 Context.Target.getPointerWidth(0)),
1245 Context.getSizeType(),
1246 SourceLocation());
1247 AllocArgs[0] = &Size;
1248 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1250 // C++ [expr.new]p8:
1251 // If the allocated type is a non-array type, the allocation
1252 // function's name is operator new and the deallocation function's
1253 // name is operator delete. If the allocated type is an array
1254 // type, the allocation function's name is operator new[] and the
1255 // deallocation function's name is operator delete[].
1256 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1257 IsArray ? OO_Array_New : OO_New);
1258 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1259 IsArray ? OO_Array_Delete : OO_Delete);
1261 QualType AllocElemType = Context.getBaseElementType(AllocType);
1263 if (AllocElemType->isRecordType() && !UseGlobal) {
1264 CXXRecordDecl *Record
1265 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1266 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1267 AllocArgs.size(), Record, /*AllowMissing=*/true,
1268 OperatorNew))
1269 return true;
1271 if (!OperatorNew) {
1272 // Didn't find a member overload. Look for a global one.
1273 DeclareGlobalNewDelete();
1274 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1275 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1276 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1277 OperatorNew))
1278 return true;
1281 // We don't need an operator delete if we're running under
1282 // -fno-exceptions.
1283 if (!getLangOptions().Exceptions) {
1284 OperatorDelete = 0;
1285 return false;
1288 // FindAllocationOverload can change the passed in arguments, so we need to
1289 // copy them back.
1290 if (NumPlaceArgs > 0)
1291 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
1293 // C++ [expr.new]p19:
1295 // If the new-expression begins with a unary :: operator, the
1296 // deallocation function's name is looked up in the global
1297 // scope. Otherwise, if the allocated type is a class type T or an
1298 // array thereof, the deallocation function's name is looked up in
1299 // the scope of T. If this lookup fails to find the name, or if
1300 // the allocated type is not a class type or array thereof, the
1301 // deallocation function's name is looked up in the global scope.
1302 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1303 if (AllocElemType->isRecordType() && !UseGlobal) {
1304 CXXRecordDecl *RD
1305 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1306 LookupQualifiedName(FoundDelete, RD);
1308 if (FoundDelete.isAmbiguous())
1309 return true; // FIXME: clean up expressions?
1311 if (FoundDelete.empty()) {
1312 DeclareGlobalNewDelete();
1313 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1316 FoundDelete.suppressDiagnostics();
1318 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1320 // Whether we're looking for a placement operator delete is dictated
1321 // by whether we selected a placement operator new, not by whether
1322 // we had explicit placement arguments. This matters for things like
1323 // struct A { void *operator new(size_t, int = 0); ... };
1324 // A *a = new A()
1325 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1327 if (isPlacementNew) {
1328 // C++ [expr.new]p20:
1329 // A declaration of a placement deallocation function matches the
1330 // declaration of a placement allocation function if it has the
1331 // same number of parameters and, after parameter transformations
1332 // (8.3.5), all parameter types except the first are
1333 // identical. [...]
1335 // To perform this comparison, we compute the function type that
1336 // the deallocation function should have, and use that type both
1337 // for template argument deduction and for comparison purposes.
1339 // FIXME: this comparison should ignore CC and the like.
1340 QualType ExpectedFunctionType;
1342 const FunctionProtoType *Proto
1343 = OperatorNew->getType()->getAs<FunctionProtoType>();
1345 llvm::SmallVector<QualType, 4> ArgTypes;
1346 ArgTypes.push_back(Context.VoidPtrTy);
1347 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1348 ArgTypes.push_back(Proto->getArgType(I));
1350 FunctionProtoType::ExtProtoInfo EPI;
1351 EPI.Variadic = Proto->isVariadic();
1353 ExpectedFunctionType
1354 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1355 ArgTypes.size(), EPI);
1358 for (LookupResult::iterator D = FoundDelete.begin(),
1359 DEnd = FoundDelete.end();
1360 D != DEnd; ++D) {
1361 FunctionDecl *Fn = 0;
1362 if (FunctionTemplateDecl *FnTmpl
1363 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1364 // Perform template argument deduction to try to match the
1365 // expected function type.
1366 TemplateDeductionInfo Info(Context, StartLoc);
1367 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1368 continue;
1369 } else
1370 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1372 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1373 Matches.push_back(std::make_pair(D.getPair(), Fn));
1375 } else {
1376 // C++ [expr.new]p20:
1377 // [...] Any non-placement deallocation function matches a
1378 // non-placement allocation function. [...]
1379 for (LookupResult::iterator D = FoundDelete.begin(),
1380 DEnd = FoundDelete.end();
1381 D != DEnd; ++D) {
1382 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1383 if (isNonPlacementDeallocationFunction(Fn))
1384 Matches.push_back(std::make_pair(D.getPair(), Fn));
1388 // C++ [expr.new]p20:
1389 // [...] If the lookup finds a single matching deallocation
1390 // function, that function will be called; otherwise, no
1391 // deallocation function will be called.
1392 if (Matches.size() == 1) {
1393 OperatorDelete = Matches[0].second;
1395 // C++0x [expr.new]p20:
1396 // If the lookup finds the two-parameter form of a usual
1397 // deallocation function (3.7.4.2) and that function, considered
1398 // as a placement deallocation function, would have been
1399 // selected as a match for the allocation function, the program
1400 // is ill-formed.
1401 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1402 isNonPlacementDeallocationFunction(OperatorDelete)) {
1403 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1404 << SourceRange(PlaceArgs[0]->getLocStart(),
1405 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1406 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1407 << DeleteName;
1408 } else {
1409 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1410 Matches[0].first);
1414 return false;
1417 /// FindAllocationOverload - Find an fitting overload for the allocation
1418 /// function in the specified scope.
1419 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1420 DeclarationName Name, Expr** Args,
1421 unsigned NumArgs, DeclContext *Ctx,
1422 bool AllowMissing, FunctionDecl *&Operator,
1423 bool Diagnose) {
1424 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1425 LookupQualifiedName(R, Ctx);
1426 if (R.empty()) {
1427 if (AllowMissing || !Diagnose)
1428 return false;
1429 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1430 << Name << Range;
1433 if (R.isAmbiguous())
1434 return true;
1436 R.suppressDiagnostics();
1438 OverloadCandidateSet Candidates(StartLoc);
1439 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1440 Alloc != AllocEnd; ++Alloc) {
1441 // Even member operator new/delete are implicitly treated as
1442 // static, so don't use AddMemberCandidate.
1443 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1445 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1446 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1447 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1448 Candidates,
1449 /*SuppressUserConversions=*/false);
1450 continue;
1453 FunctionDecl *Fn = cast<FunctionDecl>(D);
1454 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1455 /*SuppressUserConversions=*/false);
1458 // Do the resolution.
1459 OverloadCandidateSet::iterator Best;
1460 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1461 case OR_Success: {
1462 // Got one!
1463 FunctionDecl *FnDecl = Best->Function;
1464 MarkDeclarationReferenced(StartLoc, FnDecl);
1465 // The first argument is size_t, and the first parameter must be size_t,
1466 // too. This is checked on declaration and can be assumed. (It can't be
1467 // asserted on, though, since invalid decls are left in there.)
1468 // Watch out for variadic allocator function.
1469 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1470 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1471 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1472 FnDecl->getParamDecl(i));
1474 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1475 return true;
1477 ExprResult Result
1478 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
1479 if (Result.isInvalid())
1480 return true;
1482 Args[i] = Result.takeAs<Expr>();
1484 Operator = FnDecl;
1485 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1486 Diagnose);
1487 return false;
1490 case OR_No_Viable_Function:
1491 if (Diagnose) {
1492 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1493 << Name << Range;
1494 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1496 return true;
1498 case OR_Ambiguous:
1499 if (Diagnose) {
1500 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1501 << Name << Range;
1502 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1504 return true;
1506 case OR_Deleted: {
1507 if (Diagnose) {
1508 Diag(StartLoc, diag::err_ovl_deleted_call)
1509 << Best->Function->isDeleted()
1510 << Name
1511 << getDeletedOrUnavailableSuffix(Best->Function)
1512 << Range;
1513 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1515 return true;
1518 assert(false && "Unreachable, bad result from BestViableFunction");
1519 return true;
1523 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
1524 /// delete. These are:
1525 /// @code
1526 /// // C++03:
1527 /// void* operator new(std::size_t) throw(std::bad_alloc);
1528 /// void* operator new[](std::size_t) throw(std::bad_alloc);
1529 /// void operator delete(void *) throw();
1530 /// void operator delete[](void *) throw();
1531 /// // C++0x:
1532 /// void* operator new(std::size_t);
1533 /// void* operator new[](std::size_t);
1534 /// void operator delete(void *);
1535 /// void operator delete[](void *);
1536 /// @endcode
1537 /// C++0x operator delete is implicitly noexcept.
1538 /// Note that the placement and nothrow forms of new are *not* implicitly
1539 /// declared. Their use requires including \<new\>.
1540 void Sema::DeclareGlobalNewDelete() {
1541 if (GlobalNewDeleteDeclared)
1542 return;
1544 // C++ [basic.std.dynamic]p2:
1545 // [...] The following allocation and deallocation functions (18.4) are
1546 // implicitly declared in global scope in each translation unit of a
1547 // program
1549 // C++03:
1550 // void* operator new(std::size_t) throw(std::bad_alloc);
1551 // void* operator new[](std::size_t) throw(std::bad_alloc);
1552 // void operator delete(void*) throw();
1553 // void operator delete[](void*) throw();
1554 // C++0x:
1555 // void* operator new(std::size_t);
1556 // void* operator new[](std::size_t);
1557 // void operator delete(void*);
1558 // void operator delete[](void*);
1560 // These implicit declarations introduce only the function names operator
1561 // new, operator new[], operator delete, operator delete[].
1563 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1564 // "std" or "bad_alloc" as necessary to form the exception specification.
1565 // However, we do not make these implicit declarations visible to name
1566 // lookup.
1567 // Note that the C++0x versions of operator delete are deallocation functions,
1568 // and thus are implicitly noexcept.
1569 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
1570 // The "std::bad_alloc" class has not yet been declared, so build it
1571 // implicitly.
1572 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1573 getOrCreateStdNamespace(),
1574 SourceLocation(), SourceLocation(),
1575 &PP.getIdentifierTable().get("bad_alloc"),
1577 getStdBadAlloc()->setImplicit(true);
1580 GlobalNewDeleteDeclared = true;
1582 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1583 QualType SizeT = Context.getSizeType();
1584 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1586 DeclareGlobalAllocationFunction(
1587 Context.DeclarationNames.getCXXOperatorName(OO_New),
1588 VoidPtr, SizeT, AssumeSaneOperatorNew);
1589 DeclareGlobalAllocationFunction(
1590 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1591 VoidPtr, SizeT, AssumeSaneOperatorNew);
1592 DeclareGlobalAllocationFunction(
1593 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1594 Context.VoidTy, VoidPtr);
1595 DeclareGlobalAllocationFunction(
1596 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1597 Context.VoidTy, VoidPtr);
1600 /// DeclareGlobalAllocationFunction - Declares a single implicit global
1601 /// allocation function if it doesn't already exist.
1602 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1603 QualType Return, QualType Argument,
1604 bool AddMallocAttr) {
1605 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1607 // Check if this function is already declared.
1609 DeclContext::lookup_iterator Alloc, AllocEnd;
1610 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1611 Alloc != AllocEnd; ++Alloc) {
1612 // Only look at non-template functions, as it is the predefined,
1613 // non-templated allocation function we are trying to declare here.
1614 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1615 QualType InitialParamType =
1616 Context.getCanonicalType(
1617 Func->getParamDecl(0)->getType().getUnqualifiedType());
1618 // FIXME: Do we need to check for default arguments here?
1619 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1620 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
1621 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1622 return;
1628 QualType BadAllocType;
1629 bool HasBadAllocExceptionSpec
1630 = (Name.getCXXOverloadedOperator() == OO_New ||
1631 Name.getCXXOverloadedOperator() == OO_Array_New);
1632 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
1633 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1634 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
1637 FunctionProtoType::ExtProtoInfo EPI;
1638 if (HasBadAllocExceptionSpec) {
1639 if (!getLangOptions().CPlusPlus0x) {
1640 EPI.ExceptionSpecType = EST_Dynamic;
1641 EPI.NumExceptions = 1;
1642 EPI.Exceptions = &BadAllocType;
1644 } else {
1645 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1646 EST_BasicNoexcept : EST_DynamicNone;
1649 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
1650 FunctionDecl *Alloc =
1651 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1652 SourceLocation(), Name,
1653 FnType, /*TInfo=*/0, SC_None,
1654 SC_None, false, true);
1655 Alloc->setImplicit();
1657 if (AddMallocAttr)
1658 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1660 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1661 SourceLocation(), 0,
1662 Argument, /*TInfo=*/0,
1663 SC_None, SC_None, 0);
1664 Alloc->setParams(&Param, 1);
1666 // FIXME: Also add this declaration to the IdentifierResolver, but
1667 // make sure it is at the end of the chain to coincide with the
1668 // global scope.
1669 Context.getTranslationUnitDecl()->addDecl(Alloc);
1672 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1673 DeclarationName Name,
1674 FunctionDecl* &Operator, bool Diagnose) {
1675 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1676 // Try to find operator delete/operator delete[] in class scope.
1677 LookupQualifiedName(Found, RD);
1679 if (Found.isAmbiguous())
1680 return true;
1682 Found.suppressDiagnostics();
1684 llvm::SmallVector<DeclAccessPair,4> Matches;
1685 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1686 F != FEnd; ++F) {
1687 NamedDecl *ND = (*F)->getUnderlyingDecl();
1689 // Ignore template operator delete members from the check for a usual
1690 // deallocation function.
1691 if (isa<FunctionTemplateDecl>(ND))
1692 continue;
1694 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
1695 Matches.push_back(F.getPair());
1698 // There's exactly one suitable operator; pick it.
1699 if (Matches.size() == 1) {
1700 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1702 if (Operator->isDeleted()) {
1703 if (Diagnose) {
1704 Diag(StartLoc, diag::err_deleted_function_use);
1705 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1707 return true;
1710 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1711 Matches[0], Diagnose);
1712 return false;
1714 // We found multiple suitable operators; complain about the ambiguity.
1715 } else if (!Matches.empty()) {
1716 if (Diagnose) {
1717 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1718 << Name << RD;
1720 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1721 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1722 Diag((*F)->getUnderlyingDecl()->getLocation(),
1723 diag::note_member_declared_here) << Name;
1725 return true;
1728 // We did find operator delete/operator delete[] declarations, but
1729 // none of them were suitable.
1730 if (!Found.empty()) {
1731 if (Diagnose) {
1732 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1733 << Name << RD;
1735 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1736 F != FEnd; ++F)
1737 Diag((*F)->getUnderlyingDecl()->getLocation(),
1738 diag::note_member_declared_here) << Name;
1740 return true;
1743 // Look for a global declaration.
1744 DeclareGlobalNewDelete();
1745 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1747 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1748 Expr* DeallocArgs[1];
1749 DeallocArgs[0] = &Null;
1750 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1751 DeallocArgs, 1, TUDecl, !Diagnose,
1752 Operator, Diagnose))
1753 return true;
1755 assert(Operator && "Did not find a deallocation function!");
1756 return false;
1759 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1760 /// @code ::delete ptr; @endcode
1761 /// or
1762 /// @code delete [] ptr; @endcode
1763 ExprResult
1764 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1765 bool ArrayForm, Expr *ExE) {
1766 // C++ [expr.delete]p1:
1767 // The operand shall have a pointer type, or a class type having a single
1768 // conversion function to a pointer type. The result has type void.
1770 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1772 ExprResult Ex = Owned(ExE);
1773 FunctionDecl *OperatorDelete = 0;
1774 bool ArrayFormAsWritten = ArrayForm;
1775 bool UsualArrayDeleteWantsSize = false;
1777 if (!Ex.get()->isTypeDependent()) {
1778 QualType Type = Ex.get()->getType();
1780 if (const RecordType *Record = Type->getAs<RecordType>()) {
1781 if (RequireCompleteType(StartLoc, Type,
1782 PDiag(diag::err_delete_incomplete_class_type)))
1783 return ExprError();
1785 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1787 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1788 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1789 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1790 E = Conversions->end(); I != E; ++I) {
1791 NamedDecl *D = I.getDecl();
1792 if (isa<UsingShadowDecl>(D))
1793 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1795 // Skip over templated conversion functions; they aren't considered.
1796 if (isa<FunctionTemplateDecl>(D))
1797 continue;
1799 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1801 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1802 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1803 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
1804 ObjectPtrConversions.push_back(Conv);
1806 if (ObjectPtrConversions.size() == 1) {
1807 // We have a single conversion to a pointer-to-object type. Perform
1808 // that conversion.
1809 // TODO: don't redo the conversion calculation.
1810 ExprResult Res =
1811 PerformImplicitConversion(Ex.get(),
1812 ObjectPtrConversions.front()->getConversionType(),
1813 AA_Converting);
1814 if (Res.isUsable()) {
1815 Ex = move(Res);
1816 Type = Ex.get()->getType();
1819 else if (ObjectPtrConversions.size() > 1) {
1820 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1821 << Type << Ex.get()->getSourceRange();
1822 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1823 NoteOverloadCandidate(ObjectPtrConversions[i]);
1824 return ExprError();
1828 if (!Type->isPointerType())
1829 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1830 << Type << Ex.get()->getSourceRange());
1832 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1833 if (Pointee->isVoidType() && !isSFINAEContext()) {
1834 // The C++ standard bans deleting a pointer to a non-object type, which
1835 // effectively bans deletion of "void*". However, most compilers support
1836 // this, so we treat it as a warning unless we're in a SFINAE context.
1837 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1838 << Type << Ex.get()->getSourceRange();
1839 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
1840 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1841 << Type << Ex.get()->getSourceRange());
1842 else if (!Pointee->isDependentType() &&
1843 RequireCompleteType(StartLoc, Pointee,
1844 PDiag(diag::warn_delete_incomplete)
1845 << Ex.get()->getSourceRange()))
1846 return ExprError();
1847 else if (unsigned AddressSpace = Pointee.getAddressSpace())
1848 return Diag(Ex.get()->getLocStart(),
1849 diag::err_address_space_qualified_delete)
1850 << Pointee.getUnqualifiedType() << AddressSpace;
1851 // C++ [expr.delete]p2:
1852 // [Note: a pointer to a const type can be the operand of a
1853 // delete-expression; it is not necessary to cast away the constness
1854 // (5.2.11) of the pointer expression before it is used as the operand
1855 // of the delete-expression. ]
1856 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
1857 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy, CK_NoOp,
1858 Ex.take(), 0, VK_RValue));
1860 if (Pointee->isArrayType() && !ArrayForm) {
1861 Diag(StartLoc, diag::warn_delete_array_type)
1862 << Type << Ex.get()->getSourceRange()
1863 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1864 ArrayForm = true;
1867 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1868 ArrayForm ? OO_Array_Delete : OO_Delete);
1870 QualType PointeeElem = Context.getBaseElementType(Pointee);
1871 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1872 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1874 if (!UseGlobal &&
1875 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1876 return ExprError();
1878 // If we're allocating an array of records, check whether the
1879 // usual operator delete[] has a size_t parameter.
1880 if (ArrayForm) {
1881 // If the user specifically asked to use the global allocator,
1882 // we'll need to do the lookup into the class.
1883 if (UseGlobal)
1884 UsualArrayDeleteWantsSize =
1885 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1887 // Otherwise, the usual operator delete[] should be the
1888 // function we just found.
1889 else if (isa<CXXMethodDecl>(OperatorDelete))
1890 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1893 if (!RD->hasTrivialDestructor())
1894 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1895 MarkDeclarationReferenced(StartLoc,
1896 const_cast<CXXDestructorDecl*>(Dtor));
1897 DiagnoseUseOfDecl(Dtor, StartLoc);
1900 // C++ [expr.delete]p3:
1901 // In the first alternative (delete object), if the static type of the
1902 // object to be deleted is different from its dynamic type, the static
1903 // type shall be a base class of the dynamic type of the object to be
1904 // deleted and the static type shall have a virtual destructor or the
1905 // behavior is undefined.
1907 // Note: a final class cannot be derived from, no issue there
1908 if (!ArrayForm && RD->isPolymorphic() && !RD->hasAttr<FinalAttr>()) {
1909 CXXDestructorDecl *dtor = RD->getDestructor();
1910 if (!dtor || !dtor->isVirtual())
1911 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1914 } else if (getLangOptions().ObjCAutoRefCount &&
1915 PointeeElem->isObjCLifetimeType() &&
1916 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1917 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1918 ArrayForm) {
1919 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1920 << 1 << PointeeElem;
1923 if (!OperatorDelete) {
1924 // Look for a global declaration.
1925 DeclareGlobalNewDelete();
1926 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1927 Expr *Arg = Ex.get();
1928 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1929 &Arg, 1, TUDecl, /*AllowMissing=*/false,
1930 OperatorDelete))
1931 return ExprError();
1934 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1936 // Check access and ambiguity of operator delete and destructor.
1937 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1938 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1939 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1940 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
1941 PDiag(diag::err_access_dtor) << PointeeElem);
1947 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1948 ArrayFormAsWritten,
1949 UsualArrayDeleteWantsSize,
1950 OperatorDelete, Ex.take(), StartLoc));
1953 /// \brief Check the use of the given variable as a C++ condition in an if,
1954 /// while, do-while, or switch statement.
1955 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1956 SourceLocation StmtLoc,
1957 bool ConvertToBoolean) {
1958 QualType T = ConditionVar->getType();
1960 // C++ [stmt.select]p2:
1961 // The declarator shall not specify a function or an array.
1962 if (T->isFunctionType())
1963 return ExprError(Diag(ConditionVar->getLocation(),
1964 diag::err_invalid_use_of_function_type)
1965 << ConditionVar->getSourceRange());
1966 else if (T->isArrayType())
1967 return ExprError(Diag(ConditionVar->getLocation(),
1968 diag::err_invalid_use_of_array_type)
1969 << ConditionVar->getSourceRange());
1971 ExprResult Condition =
1972 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1973 ConditionVar,
1974 ConditionVar->getLocation(),
1975 ConditionVar->getType().getNonReferenceType(),
1976 VK_LValue));
1977 if (ConvertToBoolean) {
1978 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
1979 if (Condition.isInvalid())
1980 return ExprError();
1983 return move(Condition);
1986 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1987 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
1988 // C++ 6.4p4:
1989 // The value of a condition that is an initialized declaration in a statement
1990 // other than a switch statement is the value of the declared variable
1991 // implicitly converted to type bool. If that conversion is ill-formed, the
1992 // program is ill-formed.
1993 // The value of a condition that is an expression is the value of the
1994 // expression, implicitly converted to bool.
1996 return PerformContextuallyConvertToBool(CondExpr);
1999 /// Helper function to determine whether this is the (deprecated) C++
2000 /// conversion from a string literal to a pointer to non-const char or
2001 /// non-const wchar_t (for narrow and wide string literals,
2002 /// respectively).
2003 bool
2004 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2005 // Look inside the implicit cast, if it exists.
2006 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2007 From = Cast->getSubExpr();
2009 // A string literal (2.13.4) that is not a wide string literal can
2010 // be converted to an rvalue of type "pointer to char"; a wide
2011 // string literal can be converted to an rvalue of type "pointer
2012 // to wchar_t" (C++ 4.2p2).
2013 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
2014 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
2015 if (const BuiltinType *ToPointeeType
2016 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
2017 // This conversion is considered only when there is an
2018 // explicit appropriate pointer target type (C++ 4.2p2).
2019 if (!ToPtrType->getPointeeType().hasQualifiers() &&
2020 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
2021 (!StrLit->isWide() &&
2022 (ToPointeeType->getKind() == BuiltinType::Char_U ||
2023 ToPointeeType->getKind() == BuiltinType::Char_S))))
2024 return true;
2027 return false;
2030 static ExprResult BuildCXXCastArgument(Sema &S,
2031 SourceLocation CastLoc,
2032 QualType Ty,
2033 CastKind Kind,
2034 CXXMethodDecl *Method,
2035 NamedDecl *FoundDecl,
2036 Expr *From) {
2037 switch (Kind) {
2038 default: assert(0 && "Unhandled cast kind!");
2039 case CK_ConstructorConversion: {
2040 ASTOwningVector<Expr*> ConstructorArgs(S);
2042 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2043 MultiExprArg(&From, 1),
2044 CastLoc, ConstructorArgs))
2045 return ExprError();
2047 ExprResult Result =
2048 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2049 move_arg(ConstructorArgs),
2050 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
2051 SourceRange());
2052 if (Result.isInvalid())
2053 return ExprError();
2055 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2058 case CK_UserDefinedConversion: {
2059 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2061 // Create an implicit call expr that calls it.
2062 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
2063 if (Result.isInvalid())
2064 return ExprError();
2066 return S.MaybeBindToTemporary(Result.get());
2071 /// PerformImplicitConversion - Perform an implicit conversion of the
2072 /// expression From to the type ToType using the pre-computed implicit
2073 /// conversion sequence ICS. Returns the converted
2074 /// expression. Action is the kind of conversion we're performing,
2075 /// used in the error message.
2076 ExprResult
2077 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2078 const ImplicitConversionSequence &ICS,
2079 AssignmentAction Action,
2080 CheckedConversionKind CCK) {
2081 switch (ICS.getKind()) {
2082 case ImplicitConversionSequence::StandardConversion: {
2083 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2084 Action, CCK);
2085 if (Res.isInvalid())
2086 return ExprError();
2087 From = Res.take();
2088 break;
2091 case ImplicitConversionSequence::UserDefinedConversion: {
2093 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
2094 CastKind CastKind;
2095 QualType BeforeToType;
2096 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
2097 CastKind = CK_UserDefinedConversion;
2099 // If the user-defined conversion is specified by a conversion function,
2100 // the initial standard conversion sequence converts the source type to
2101 // the implicit object parameter of the conversion function.
2102 BeforeToType = Context.getTagDeclType(Conv->getParent());
2103 } else {
2104 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
2105 CastKind = CK_ConstructorConversion;
2106 // Do no conversion if dealing with ... for the first conversion.
2107 if (!ICS.UserDefined.EllipsisConversion) {
2108 // If the user-defined conversion is specified by a constructor, the
2109 // initial standard conversion sequence converts the source type to the
2110 // type required by the argument of the constructor
2111 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2114 // Watch out for elipsis conversion.
2115 if (!ICS.UserDefined.EllipsisConversion) {
2116 ExprResult Res =
2117 PerformImplicitConversion(From, BeforeToType,
2118 ICS.UserDefined.Before, AA_Converting,
2119 CCK);
2120 if (Res.isInvalid())
2121 return ExprError();
2122 From = Res.take();
2125 ExprResult CastArg
2126 = BuildCXXCastArgument(*this,
2127 From->getLocStart(),
2128 ToType.getNonReferenceType(),
2129 CastKind, cast<CXXMethodDecl>(FD),
2130 ICS.UserDefined.FoundConversionFunction,
2131 From);
2133 if (CastArg.isInvalid())
2134 return ExprError();
2136 From = CastArg.take();
2138 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2139 AA_Converting, CCK);
2142 case ImplicitConversionSequence::AmbiguousConversion:
2143 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2144 PDiag(diag::err_typecheck_ambiguous_condition)
2145 << From->getSourceRange());
2146 return ExprError();
2148 case ImplicitConversionSequence::EllipsisConversion:
2149 assert(false && "Cannot perform an ellipsis conversion");
2150 return Owned(From);
2152 case ImplicitConversionSequence::BadConversion:
2153 return ExprError();
2156 // Everything went well.
2157 return Owned(From);
2160 /// PerformImplicitConversion - Perform an implicit conversion of the
2161 /// expression From to the type ToType by following the standard
2162 /// conversion sequence SCS. Returns the converted
2163 /// expression. Flavor is the context in which we're performing this
2164 /// conversion, for use in error messages.
2165 ExprResult
2166 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2167 const StandardConversionSequence& SCS,
2168 AssignmentAction Action,
2169 CheckedConversionKind CCK) {
2170 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2172 // Overall FIXME: we are recomputing too many types here and doing far too
2173 // much extra work. What this means is that we need to keep track of more
2174 // information that is computed when we try the implicit conversion initially,
2175 // so that we don't need to recompute anything here.
2176 QualType FromType = From->getType();
2178 if (SCS.CopyConstructor) {
2179 // FIXME: When can ToType be a reference type?
2180 assert(!ToType->isReferenceType());
2181 if (SCS.Second == ICK_Derived_To_Base) {
2182 ASTOwningVector<Expr*> ConstructorArgs(*this);
2183 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2184 MultiExprArg(*this, &From, 1),
2185 /*FIXME:ConstructLoc*/SourceLocation(),
2186 ConstructorArgs))
2187 return ExprError();
2188 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2189 ToType, SCS.CopyConstructor,
2190 move_arg(ConstructorArgs),
2191 /*ZeroInit*/ false,
2192 CXXConstructExpr::CK_Complete,
2193 SourceRange());
2195 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2196 ToType, SCS.CopyConstructor,
2197 MultiExprArg(*this, &From, 1),
2198 /*ZeroInit*/ false,
2199 CXXConstructExpr::CK_Complete,
2200 SourceRange());
2203 // Resolve overloaded function references.
2204 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2205 DeclAccessPair Found;
2206 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2207 true, Found);
2208 if (!Fn)
2209 return ExprError();
2211 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2212 return ExprError();
2214 From = FixOverloadedFunctionReference(From, Found, Fn);
2215 FromType = From->getType();
2218 // Perform the first implicit conversion.
2219 switch (SCS.First) {
2220 case ICK_Identity:
2221 // Nothing to do.
2222 break;
2224 case ICK_Lvalue_To_Rvalue:
2225 // Should this get its own ICK?
2226 if (From->getObjectKind() == OK_ObjCProperty) {
2227 ExprResult FromRes = ConvertPropertyForRValue(From);
2228 if (FromRes.isInvalid())
2229 return ExprError();
2230 From = FromRes.take();
2231 if (!From->isGLValue()) break;
2234 // Check for trivial buffer overflows.
2235 CheckArrayAccess(From);
2237 FromType = FromType.getUnqualifiedType();
2238 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2239 From, 0, VK_RValue);
2240 break;
2242 case ICK_Array_To_Pointer:
2243 FromType = Context.getArrayDecayedType(FromType);
2244 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2245 VK_RValue, /*BasePath=*/0, CCK).take();
2246 break;
2248 case ICK_Function_To_Pointer:
2249 FromType = Context.getPointerType(FromType);
2250 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2251 VK_RValue, /*BasePath=*/0, CCK).take();
2252 break;
2254 default:
2255 assert(false && "Improper first standard conversion");
2256 break;
2259 // Perform the second implicit conversion
2260 switch (SCS.Second) {
2261 case ICK_Identity:
2262 // If both sides are functions (or pointers/references to them), there could
2263 // be incompatible exception declarations.
2264 if (CheckExceptionSpecCompatibility(From, ToType))
2265 return ExprError();
2266 // Nothing else to do.
2267 break;
2269 case ICK_NoReturn_Adjustment:
2270 // If both sides are functions (or pointers/references to them), there could
2271 // be incompatible exception declarations.
2272 if (CheckExceptionSpecCompatibility(From, ToType))
2273 return ExprError();
2275 From = ImpCastExprToType(From, ToType, CK_NoOp,
2276 VK_RValue, /*BasePath=*/0, CCK).take();
2277 break;
2279 case ICK_Integral_Promotion:
2280 case ICK_Integral_Conversion:
2281 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2282 VK_RValue, /*BasePath=*/0, CCK).take();
2283 break;
2285 case ICK_Floating_Promotion:
2286 case ICK_Floating_Conversion:
2287 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2288 VK_RValue, /*BasePath=*/0, CCK).take();
2289 break;
2291 case ICK_Complex_Promotion:
2292 case ICK_Complex_Conversion: {
2293 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2294 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2295 CastKind CK;
2296 if (FromEl->isRealFloatingType()) {
2297 if (ToEl->isRealFloatingType())
2298 CK = CK_FloatingComplexCast;
2299 else
2300 CK = CK_FloatingComplexToIntegralComplex;
2301 } else if (ToEl->isRealFloatingType()) {
2302 CK = CK_IntegralComplexToFloatingComplex;
2303 } else {
2304 CK = CK_IntegralComplexCast;
2306 From = ImpCastExprToType(From, ToType, CK,
2307 VK_RValue, /*BasePath=*/0, CCK).take();
2308 break;
2311 case ICK_Floating_Integral:
2312 if (ToType->isRealFloatingType())
2313 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2314 VK_RValue, /*BasePath=*/0, CCK).take();
2315 else
2316 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2317 VK_RValue, /*BasePath=*/0, CCK).take();
2318 break;
2320 case ICK_Compatible_Conversion:
2321 From = ImpCastExprToType(From, ToType, CK_NoOp,
2322 VK_RValue, /*BasePath=*/0, CCK).take();
2323 break;
2325 case ICK_Writeback_Conversion:
2326 case ICK_Pointer_Conversion: {
2327 if (SCS.IncompatibleObjC && Action != AA_Casting) {
2328 // Diagnose incompatible Objective-C conversions
2329 if (Action == AA_Initializing || Action == AA_Assigning)
2330 Diag(From->getSourceRange().getBegin(),
2331 diag::ext_typecheck_convert_incompatible_pointer)
2332 << ToType << From->getType() << Action
2333 << From->getSourceRange();
2334 else
2335 Diag(From->getSourceRange().getBegin(),
2336 diag::ext_typecheck_convert_incompatible_pointer)
2337 << From->getType() << ToType << Action
2338 << From->getSourceRange();
2340 if (From->getType()->isObjCObjectPointerType() &&
2341 ToType->isObjCObjectPointerType())
2342 EmitRelatedResultTypeNote(From);
2344 else if (getLangOptions().ObjCAutoRefCount &&
2345 !CheckObjCARCUnavailableWeakConversion(ToType,
2346 From->getType())) {
2347 if (Action == AA_Initializing)
2348 Diag(From->getSourceRange().getBegin(),
2349 diag::err_arc_weak_unavailable_assign);
2350 else
2351 Diag(From->getSourceRange().getBegin(),
2352 diag::err_arc_convesion_of_weak_unavailable)
2353 << (Action == AA_Casting) << From->getType() << ToType
2354 << From->getSourceRange();
2357 CastKind Kind = CK_Invalid;
2358 CXXCastPath BasePath;
2359 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2360 return ExprError();
2361 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2362 .take();
2363 break;
2366 case ICK_Pointer_Member: {
2367 CastKind Kind = CK_Invalid;
2368 CXXCastPath BasePath;
2369 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2370 return ExprError();
2371 if (CheckExceptionSpecCompatibility(From, ToType))
2372 return ExprError();
2373 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2374 .take();
2375 break;
2378 case ICK_Boolean_Conversion:
2379 From = ImpCastExprToType(From, Context.BoolTy,
2380 ScalarTypeToBooleanCastKind(FromType),
2381 VK_RValue, /*BasePath=*/0, CCK).take();
2382 break;
2384 case ICK_Derived_To_Base: {
2385 CXXCastPath BasePath;
2386 if (CheckDerivedToBaseConversion(From->getType(),
2387 ToType.getNonReferenceType(),
2388 From->getLocStart(),
2389 From->getSourceRange(),
2390 &BasePath,
2391 CStyle))
2392 return ExprError();
2394 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2395 CK_DerivedToBase, CastCategory(From),
2396 &BasePath, CCK).take();
2397 break;
2400 case ICK_Vector_Conversion:
2401 From = ImpCastExprToType(From, ToType, CK_BitCast,
2402 VK_RValue, /*BasePath=*/0, CCK).take();
2403 break;
2405 case ICK_Vector_Splat:
2406 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2407 VK_RValue, /*BasePath=*/0, CCK).take();
2408 break;
2410 case ICK_Complex_Real:
2411 // Case 1. x -> _Complex y
2412 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2413 QualType ElType = ToComplex->getElementType();
2414 bool isFloatingComplex = ElType->isRealFloatingType();
2416 // x -> y
2417 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2418 // do nothing
2419 } else if (From->getType()->isRealFloatingType()) {
2420 From = ImpCastExprToType(From, ElType,
2421 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
2422 } else {
2423 assert(From->getType()->isIntegerType());
2424 From = ImpCastExprToType(From, ElType,
2425 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
2427 // y -> _Complex y
2428 From = ImpCastExprToType(From, ToType,
2429 isFloatingComplex ? CK_FloatingRealToComplex
2430 : CK_IntegralRealToComplex).take();
2432 // Case 2. _Complex x -> y
2433 } else {
2434 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2435 assert(FromComplex);
2437 QualType ElType = FromComplex->getElementType();
2438 bool isFloatingComplex = ElType->isRealFloatingType();
2440 // _Complex x -> x
2441 From = ImpCastExprToType(From, ElType,
2442 isFloatingComplex ? CK_FloatingComplexToReal
2443 : CK_IntegralComplexToReal,
2444 VK_RValue, /*BasePath=*/0, CCK).take();
2446 // x -> y
2447 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2448 // do nothing
2449 } else if (ToType->isRealFloatingType()) {
2450 From = ImpCastExprToType(From, ToType,
2451 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2452 VK_RValue, /*BasePath=*/0, CCK).take();
2453 } else {
2454 assert(ToType->isIntegerType());
2455 From = ImpCastExprToType(From, ToType,
2456 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2457 VK_RValue, /*BasePath=*/0, CCK).take();
2460 break;
2462 case ICK_Block_Pointer_Conversion: {
2463 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2464 VK_RValue, /*BasePath=*/0, CCK).take();
2465 break;
2468 case ICK_TransparentUnionConversion: {
2469 ExprResult FromRes = Owned(From);
2470 Sema::AssignConvertType ConvTy =
2471 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2472 if (FromRes.isInvalid())
2473 return ExprError();
2474 From = FromRes.take();
2475 assert ((ConvTy == Sema::Compatible) &&
2476 "Improper transparent union conversion");
2477 (void)ConvTy;
2478 break;
2481 case ICK_Lvalue_To_Rvalue:
2482 case ICK_Array_To_Pointer:
2483 case ICK_Function_To_Pointer:
2484 case ICK_Qualification:
2485 case ICK_Num_Conversion_Kinds:
2486 assert(false && "Improper second standard conversion");
2487 break;
2490 switch (SCS.Third) {
2491 case ICK_Identity:
2492 // Nothing to do.
2493 break;
2495 case ICK_Qualification: {
2496 // The qualification keeps the category of the inner expression, unless the
2497 // target type isn't a reference.
2498 ExprValueKind VK = ToType->isReferenceType() ?
2499 CastCategory(From) : VK_RValue;
2500 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2501 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
2503 if (SCS.DeprecatedStringLiteralToCharPtr &&
2504 !getLangOptions().WritableStrings)
2505 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2506 << ToType.getNonReferenceType();
2508 break;
2511 default:
2512 assert(false && "Improper third standard conversion");
2513 break;
2516 return Owned(From);
2519 ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
2520 SourceLocation KWLoc,
2521 ParsedType Ty,
2522 SourceLocation RParen) {
2523 TypeSourceInfo *TSInfo;
2524 QualType T = GetTypeFromParser(Ty, &TSInfo);
2526 if (!TSInfo)
2527 TSInfo = Context.getTrivialTypeSourceInfo(T);
2528 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
2531 /// \brief Check the completeness of a type in a unary type trait.
2533 /// If the particular type trait requires a complete type, tries to complete
2534 /// it. If completing the type fails, a diagnostic is emitted and false
2535 /// returned. If completing the type succeeds or no completion was required,
2536 /// returns true.
2537 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2538 UnaryTypeTrait UTT,
2539 SourceLocation Loc,
2540 QualType ArgTy) {
2541 // C++0x [meta.unary.prop]p3:
2542 // For all of the class templates X declared in this Clause, instantiating
2543 // that template with a template argument that is a class template
2544 // specialization may result in the implicit instantiation of the template
2545 // argument if and only if the semantics of X require that the argument
2546 // must be a complete type.
2547 // We apply this rule to all the type trait expressions used to implement
2548 // these class templates. We also try to follow any GCC documented behavior
2549 // in these expressions to ensure portability of standard libraries.
2550 switch (UTT) {
2551 // is_complete_type somewhat obviously cannot require a complete type.
2552 case UTT_IsCompleteType:
2553 // Fall-through
2555 // These traits are modeled on the type predicates in C++0x
2556 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2557 // requiring a complete type, as whether or not they return true cannot be
2558 // impacted by the completeness of the type.
2559 case UTT_IsVoid:
2560 case UTT_IsIntegral:
2561 case UTT_IsFloatingPoint:
2562 case UTT_IsArray:
2563 case UTT_IsPointer:
2564 case UTT_IsLvalueReference:
2565 case UTT_IsRvalueReference:
2566 case UTT_IsMemberFunctionPointer:
2567 case UTT_IsMemberObjectPointer:
2568 case UTT_IsEnum:
2569 case UTT_IsUnion:
2570 case UTT_IsClass:
2571 case UTT_IsFunction:
2572 case UTT_IsReference:
2573 case UTT_IsArithmetic:
2574 case UTT_IsFundamental:
2575 case UTT_IsObject:
2576 case UTT_IsScalar:
2577 case UTT_IsCompound:
2578 case UTT_IsMemberPointer:
2579 // Fall-through
2581 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2582 // which requires some of its traits to have the complete type. However,
2583 // the completeness of the type cannot impact these traits' semantics, and
2584 // so they don't require it. This matches the comments on these traits in
2585 // Table 49.
2586 case UTT_IsConst:
2587 case UTT_IsVolatile:
2588 case UTT_IsSigned:
2589 case UTT_IsUnsigned:
2590 return true;
2592 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
2593 // applied to a complete type.
2594 case UTT_IsTrivial:
2595 case UTT_IsTriviallyCopyable:
2596 case UTT_IsStandardLayout:
2597 case UTT_IsPOD:
2598 case UTT_IsLiteral:
2599 case UTT_IsEmpty:
2600 case UTT_IsPolymorphic:
2601 case UTT_IsAbstract:
2602 // Fall-through
2604 // These trait expressions are designed to help implement predicates in
2605 // [meta.unary.prop] despite not being named the same. They are specified
2606 // by both GCC and the Embarcadero C++ compiler, and require the complete
2607 // type due to the overarching C++0x type predicates being implemented
2608 // requiring the complete type.
2609 case UTT_HasNothrowAssign:
2610 case UTT_HasNothrowConstructor:
2611 case UTT_HasNothrowCopy:
2612 case UTT_HasTrivialAssign:
2613 case UTT_HasTrivialDefaultConstructor:
2614 case UTT_HasTrivialCopy:
2615 case UTT_HasTrivialDestructor:
2616 case UTT_HasVirtualDestructor:
2617 // Arrays of unknown bound are expressly allowed.
2618 QualType ElTy = ArgTy;
2619 if (ArgTy->isIncompleteArrayType())
2620 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2622 // The void type is expressly allowed.
2623 if (ElTy->isVoidType())
2624 return true;
2626 return !S.RequireCompleteType(
2627 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
2629 llvm_unreachable("Type trait not handled by switch");
2632 static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2633 SourceLocation KeyLoc, QualType T) {
2634 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
2636 ASTContext &C = Self.Context;
2637 switch(UTT) {
2638 // Type trait expressions corresponding to the primary type category
2639 // predicates in C++0x [meta.unary.cat].
2640 case UTT_IsVoid:
2641 return T->isVoidType();
2642 case UTT_IsIntegral:
2643 return T->isIntegralType(C);
2644 case UTT_IsFloatingPoint:
2645 return T->isFloatingType();
2646 case UTT_IsArray:
2647 return T->isArrayType();
2648 case UTT_IsPointer:
2649 return T->isPointerType();
2650 case UTT_IsLvalueReference:
2651 return T->isLValueReferenceType();
2652 case UTT_IsRvalueReference:
2653 return T->isRValueReferenceType();
2654 case UTT_IsMemberFunctionPointer:
2655 return T->isMemberFunctionPointerType();
2656 case UTT_IsMemberObjectPointer:
2657 return T->isMemberDataPointerType();
2658 case UTT_IsEnum:
2659 return T->isEnumeralType();
2660 case UTT_IsUnion:
2661 return T->isUnionType();
2662 case UTT_IsClass:
2663 return T->isClassType() || T->isStructureType();
2664 case UTT_IsFunction:
2665 return T->isFunctionType();
2667 // Type trait expressions which correspond to the convenient composition
2668 // predicates in C++0x [meta.unary.comp].
2669 case UTT_IsReference:
2670 return T->isReferenceType();
2671 case UTT_IsArithmetic:
2672 return T->isArithmeticType() && !T->isEnumeralType();
2673 case UTT_IsFundamental:
2674 return T->isFundamentalType();
2675 case UTT_IsObject:
2676 return T->isObjectType();
2677 case UTT_IsScalar:
2678 // Note: semantic analysis depends on Objective-C lifetime types to be
2679 // considered scalar types. However, such types do not actually behave
2680 // like scalar types at run time (since they may require retain/release
2681 // operations), so we report them as non-scalar.
2682 if (T->isObjCLifetimeType()) {
2683 switch (T.getObjCLifetime()) {
2684 case Qualifiers::OCL_None:
2685 case Qualifiers::OCL_ExplicitNone:
2686 return true;
2688 case Qualifiers::OCL_Strong:
2689 case Qualifiers::OCL_Weak:
2690 case Qualifiers::OCL_Autoreleasing:
2691 return false;
2695 return T->isScalarType();
2696 case UTT_IsCompound:
2697 return T->isCompoundType();
2698 case UTT_IsMemberPointer:
2699 return T->isMemberPointerType();
2701 // Type trait expressions which correspond to the type property predicates
2702 // in C++0x [meta.unary.prop].
2703 case UTT_IsConst:
2704 return T.isConstQualified();
2705 case UTT_IsVolatile:
2706 return T.isVolatileQualified();
2707 case UTT_IsTrivial:
2708 return T.isTrivialType(Self.Context);
2709 case UTT_IsTriviallyCopyable:
2710 return T.isTriviallyCopyableType(Self.Context);
2711 case UTT_IsStandardLayout:
2712 return T->isStandardLayoutType();
2713 case UTT_IsPOD:
2714 return T.isPODType(Self.Context);
2715 case UTT_IsLiteral:
2716 return T->isLiteralType();
2717 case UTT_IsEmpty:
2718 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2719 return !RD->isUnion() && RD->isEmpty();
2720 return false;
2721 case UTT_IsPolymorphic:
2722 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2723 return RD->isPolymorphic();
2724 return false;
2725 case UTT_IsAbstract:
2726 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2727 return RD->isAbstract();
2728 return false;
2729 case UTT_IsSigned:
2730 return T->isSignedIntegerType();
2731 case UTT_IsUnsigned:
2732 return T->isUnsignedIntegerType();
2734 // Type trait expressions which query classes regarding their construction,
2735 // destruction, and copying. Rather than being based directly on the
2736 // related type predicates in the standard, they are specified by both
2737 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2738 // specifications.
2740 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2741 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2742 case UTT_HasTrivialDefaultConstructor:
2743 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2744 // If __is_pod (type) is true then the trait is true, else if type is
2745 // a cv class or union type (or array thereof) with a trivial default
2746 // constructor ([class.ctor]) then the trait is true, else it is false.
2747 if (T.isPODType(Self.Context))
2748 return true;
2749 if (const RecordType *RT =
2750 C.getBaseElementType(T)->getAs<RecordType>())
2751 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
2752 return false;
2753 case UTT_HasTrivialCopy:
2754 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2755 // If __is_pod (type) is true or type is a reference type then
2756 // the trait is true, else if type is a cv class or union type
2757 // with a trivial copy constructor ([class.copy]) then the trait
2758 // is true, else it is false.
2759 if (T.isPODType(Self.Context) || T->isReferenceType())
2760 return true;
2761 if (const RecordType *RT = T->getAs<RecordType>())
2762 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2763 return false;
2764 case UTT_HasTrivialAssign:
2765 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2766 // If type is const qualified or is a reference type then the
2767 // trait is false. Otherwise if __is_pod (type) is true then the
2768 // trait is true, else if type is a cv class or union type with
2769 // a trivial copy assignment ([class.copy]) then the trait is
2770 // true, else it is false.
2771 // Note: the const and reference restrictions are interesting,
2772 // given that const and reference members don't prevent a class
2773 // from having a trivial copy assignment operator (but do cause
2774 // errors if the copy assignment operator is actually used, q.v.
2775 // [class.copy]p12).
2777 if (C.getBaseElementType(T).isConstQualified())
2778 return false;
2779 if (T.isPODType(Self.Context))
2780 return true;
2781 if (const RecordType *RT = T->getAs<RecordType>())
2782 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2783 return false;
2784 case UTT_HasTrivialDestructor:
2785 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2786 // If __is_pod (type) is true or type is a reference type
2787 // then the trait is true, else if type is a cv class or union
2788 // type (or array thereof) with a trivial destructor
2789 // ([class.dtor]) then the trait is true, else it is
2790 // false.
2791 if (T.isPODType(Self.Context) || T->isReferenceType())
2792 return true;
2794 // Objective-C++ ARC: autorelease types don't require destruction.
2795 if (T->isObjCLifetimeType() &&
2796 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2797 return true;
2799 if (const RecordType *RT =
2800 C.getBaseElementType(T)->getAs<RecordType>())
2801 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2802 return false;
2803 // TODO: Propagate nothrowness for implicitly declared special members.
2804 case UTT_HasNothrowAssign:
2805 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2806 // If type is const qualified or is a reference type then the
2807 // trait is false. Otherwise if __has_trivial_assign (type)
2808 // is true then the trait is true, else if type is a cv class
2809 // or union type with copy assignment operators that are known
2810 // not to throw an exception then the trait is true, else it is
2811 // false.
2812 if (C.getBaseElementType(T).isConstQualified())
2813 return false;
2814 if (T->isReferenceType())
2815 return false;
2816 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2817 return true;
2818 if (const RecordType *RT = T->getAs<RecordType>()) {
2819 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2820 if (RD->hasTrivialCopyAssignment())
2821 return true;
2823 bool FoundAssign = false;
2824 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
2825 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2826 Sema::LookupOrdinaryName);
2827 if (Self.LookupQualifiedName(Res, RD)) {
2828 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2829 Op != OpEnd; ++Op) {
2830 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2831 if (Operator->isCopyAssignmentOperator()) {
2832 FoundAssign = true;
2833 const FunctionProtoType *CPT
2834 = Operator->getType()->getAs<FunctionProtoType>();
2835 if (CPT->getExceptionSpecType() == EST_Delayed)
2836 return false;
2837 if (!CPT->isNothrow(Self.Context))
2838 return false;
2843 return FoundAssign;
2845 return false;
2846 case UTT_HasNothrowCopy:
2847 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2848 // If __has_trivial_copy (type) is true then the trait is true, else
2849 // if type is a cv class or union type with copy constructors that are
2850 // known not to throw an exception then the trait is true, else it is
2851 // false.
2852 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
2853 return true;
2854 if (const RecordType *RT = T->getAs<RecordType>()) {
2855 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2856 if (RD->hasTrivialCopyConstructor())
2857 return true;
2859 bool FoundConstructor = false;
2860 unsigned FoundTQs;
2861 DeclContext::lookup_const_iterator Con, ConEnd;
2862 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2863 Con != ConEnd; ++Con) {
2864 // A template constructor is never a copy constructor.
2865 // FIXME: However, it may actually be selected at the actual overload
2866 // resolution point.
2867 if (isa<FunctionTemplateDecl>(*Con))
2868 continue;
2869 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2870 if (Constructor->isCopyConstructor(FoundTQs)) {
2871 FoundConstructor = true;
2872 const FunctionProtoType *CPT
2873 = Constructor->getType()->getAs<FunctionProtoType>();
2874 if (CPT->getExceptionSpecType() == EST_Delayed)
2875 return false;
2876 // FIXME: check whether evaluating default arguments can throw.
2877 // For now, we'll be conservative and assume that they can throw.
2878 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2879 return false;
2883 return FoundConstructor;
2885 return false;
2886 case UTT_HasNothrowConstructor:
2887 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2888 // If __has_trivial_constructor (type) is true then the trait is
2889 // true, else if type is a cv class or union type (or array
2890 // thereof) with a default constructor that is known not to
2891 // throw an exception then the trait is true, else it is false.
2892 if (T.isPODType(C) || T->isObjCLifetimeType())
2893 return true;
2894 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2895 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2896 if (RD->hasTrivialDefaultConstructor())
2897 return true;
2899 DeclContext::lookup_const_iterator Con, ConEnd;
2900 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2901 Con != ConEnd; ++Con) {
2902 // FIXME: In C++0x, a constructor template can be a default constructor.
2903 if (isa<FunctionTemplateDecl>(*Con))
2904 continue;
2905 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2906 if (Constructor->isDefaultConstructor()) {
2907 const FunctionProtoType *CPT
2908 = Constructor->getType()->getAs<FunctionProtoType>();
2909 if (CPT->getExceptionSpecType() == EST_Delayed)
2910 return false;
2911 // TODO: check whether evaluating default arguments can throw.
2912 // For now, we'll be conservative and assume that they can throw.
2913 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
2917 return false;
2918 case UTT_HasVirtualDestructor:
2919 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2920 // If type is a class type with a virtual destructor ([class.dtor])
2921 // then the trait is true, else it is false.
2922 if (const RecordType *Record = T->getAs<RecordType>()) {
2923 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2924 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
2925 return Destructor->isVirtual();
2927 return false;
2929 // These type trait expressions are modeled on the specifications for the
2930 // Embarcadero C++0x type trait functions:
2931 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2932 case UTT_IsCompleteType:
2933 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
2934 // Returns True if and only if T is a complete type at the point of the
2935 // function call.
2936 return !T->isIncompleteType();
2938 llvm_unreachable("Type trait not covered by switch");
2941 ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
2942 SourceLocation KWLoc,
2943 TypeSourceInfo *TSInfo,
2944 SourceLocation RParen) {
2945 QualType T = TSInfo->getType();
2946 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
2947 return ExprError();
2949 bool Value = false;
2950 if (!T->isDependentType())
2951 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
2953 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
2954 RParen, Context.BoolTy));
2957 ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2958 SourceLocation KWLoc,
2959 ParsedType LhsTy,
2960 ParsedType RhsTy,
2961 SourceLocation RParen) {
2962 TypeSourceInfo *LhsTSInfo;
2963 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2964 if (!LhsTSInfo)
2965 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2967 TypeSourceInfo *RhsTSInfo;
2968 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2969 if (!RhsTSInfo)
2970 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2972 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2975 static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2976 QualType LhsT, QualType RhsT,
2977 SourceLocation KeyLoc) {
2978 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
2979 "Cannot evaluate traits of dependent types");
2981 switch(BTT) {
2982 case BTT_IsBaseOf: {
2983 // C++0x [meta.rel]p2
2984 // Base is a base class of Derived without regard to cv-qualifiers or
2985 // Base and Derived are not unions and name the same class type without
2986 // regard to cv-qualifiers.
2988 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2989 if (!lhsRecord) return false;
2991 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2992 if (!rhsRecord) return false;
2994 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2995 == (lhsRecord == rhsRecord));
2997 if (lhsRecord == rhsRecord)
2998 return !lhsRecord->getDecl()->isUnion();
3000 // C++0x [meta.rel]p2:
3001 // If Base and Derived are class types and are different types
3002 // (ignoring possible cv-qualifiers) then Derived shall be a
3003 // complete type.
3004 if (Self.RequireCompleteType(KeyLoc, RhsT,
3005 diag::err_incomplete_type_used_in_type_trait_expr))
3006 return false;
3008 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3009 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3011 case BTT_IsSame:
3012 return Self.Context.hasSameType(LhsT, RhsT);
3013 case BTT_TypeCompatible:
3014 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3015 RhsT.getUnqualifiedType());
3016 case BTT_IsConvertible:
3017 case BTT_IsConvertibleTo: {
3018 // C++0x [meta.rel]p4:
3019 // Given the following function prototype:
3021 // template <class T>
3022 // typename add_rvalue_reference<T>::type create();
3024 // the predicate condition for a template specialization
3025 // is_convertible<From, To> shall be satisfied if and only if
3026 // the return expression in the following code would be
3027 // well-formed, including any implicit conversions to the return
3028 // type of the function:
3030 // To test() {
3031 // return create<From>();
3032 // }
3034 // Access checking is performed as if in a context unrelated to To and
3035 // From. Only the validity of the immediate context of the expression
3036 // of the return-statement (including conversions to the return type)
3037 // is considered.
3039 // We model the initialization as a copy-initialization of a temporary
3040 // of the appropriate type, which for this expression is identical to the
3041 // return statement (since NRVO doesn't apply).
3042 if (LhsT->isObjectType() || LhsT->isFunctionType())
3043 LhsT = Self.Context.getRValueReferenceType(LhsT);
3045 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
3046 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3047 Expr::getValueKindForType(LhsT));
3048 Expr *FromPtr = &From;
3049 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3050 SourceLocation()));
3052 // Perform the initialization within a SFINAE trap at translation unit
3053 // scope.
3054 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3055 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3056 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
3057 if (Init.Failed())
3058 return false;
3060 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3061 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3064 llvm_unreachable("Unknown type trait or not implemented");
3067 ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3068 SourceLocation KWLoc,
3069 TypeSourceInfo *LhsTSInfo,
3070 TypeSourceInfo *RhsTSInfo,
3071 SourceLocation RParen) {
3072 QualType LhsT = LhsTSInfo->getType();
3073 QualType RhsT = RhsTSInfo->getType();
3075 if (BTT == BTT_TypeCompatible) {
3076 if (getLangOptions().CPlusPlus) {
3077 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3078 << SourceRange(KWLoc, RParen);
3079 return ExprError();
3083 bool Value = false;
3084 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3085 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3087 // Select trait result type.
3088 QualType ResultType;
3089 switch (BTT) {
3090 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
3091 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3092 case BTT_IsSame: ResultType = Context.BoolTy; break;
3093 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
3094 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
3097 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3098 RhsTSInfo, Value, RParen,
3099 ResultType));
3102 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3103 SourceLocation KWLoc,
3104 ParsedType Ty,
3105 Expr* DimExpr,
3106 SourceLocation RParen) {
3107 TypeSourceInfo *TSInfo;
3108 QualType T = GetTypeFromParser(Ty, &TSInfo);
3109 if (!TSInfo)
3110 TSInfo = Context.getTrivialTypeSourceInfo(T);
3112 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3115 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3116 QualType T, Expr *DimExpr,
3117 SourceLocation KeyLoc) {
3118 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3120 switch(ATT) {
3121 case ATT_ArrayRank:
3122 if (T->isArrayType()) {
3123 unsigned Dim = 0;
3124 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3125 ++Dim;
3126 T = AT->getElementType();
3128 return Dim;
3130 return 0;
3132 case ATT_ArrayExtent: {
3133 llvm::APSInt Value;
3134 uint64_t Dim;
3135 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3136 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3137 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3138 DimExpr->getSourceRange();
3139 return false;
3141 Dim = Value.getLimitedValue();
3142 } else {
3143 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3144 DimExpr->getSourceRange();
3145 return false;
3148 if (T->isArrayType()) {
3149 unsigned D = 0;
3150 bool Matched = false;
3151 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3152 if (Dim == D) {
3153 Matched = true;
3154 break;
3156 ++D;
3157 T = AT->getElementType();
3160 if (Matched && T->isArrayType()) {
3161 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3162 return CAT->getSize().getLimitedValue();
3165 return 0;
3168 llvm_unreachable("Unknown type trait or not implemented");
3171 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3172 SourceLocation KWLoc,
3173 TypeSourceInfo *TSInfo,
3174 Expr* DimExpr,
3175 SourceLocation RParen) {
3176 QualType T = TSInfo->getType();
3178 // FIXME: This should likely be tracked as an APInt to remove any host
3179 // assumptions about the width of size_t on the target.
3180 uint64_t Value = 0;
3181 if (!T->isDependentType())
3182 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3184 // While the specification for these traits from the Embarcadero C++
3185 // compiler's documentation says the return type is 'unsigned int', Clang
3186 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3187 // compiler, there is no difference. On several other platforms this is an
3188 // important distinction.
3189 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
3190 DimExpr, RParen,
3191 Context.getSizeType()));
3194 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
3195 SourceLocation KWLoc,
3196 Expr *Queried,
3197 SourceLocation RParen) {
3198 // If error parsing the expression, ignore.
3199 if (!Queried)
3200 return ExprError();
3202 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
3204 return move(Result);
3207 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3208 switch (ET) {
3209 case ET_IsLValueExpr: return E->isLValue();
3210 case ET_IsRValueExpr: return E->isRValue();
3212 llvm_unreachable("Expression trait not covered by switch");
3215 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
3216 SourceLocation KWLoc,
3217 Expr *Queried,
3218 SourceLocation RParen) {
3219 if (Queried->isTypeDependent()) {
3220 // Delay type-checking for type-dependent expressions.
3221 } else if (Queried->getType()->isPlaceholderType()) {
3222 ExprResult PE = CheckPlaceholderExpr(Queried);
3223 if (PE.isInvalid()) return ExprError();
3224 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3227 bool Value = EvaluateExpressionTrait(ET, Queried);
3229 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3230 RParen, Context.BoolTy));
3233 QualType Sema::CheckPointerToMemberOperands(ExprResult &lex, ExprResult &rex,
3234 ExprValueKind &VK,
3235 SourceLocation Loc,
3236 bool isIndirect) {
3237 assert(!lex.get()->getType()->isPlaceholderType() &&
3238 !rex.get()->getType()->isPlaceholderType() &&
3239 "placeholders should have been weeded out by now");
3241 // The LHS undergoes lvalue conversions if this is ->*.
3242 if (isIndirect) {
3243 lex = DefaultLvalueConversion(lex.take());
3244 if (lex.isInvalid()) return QualType();
3247 // The RHS always undergoes lvalue conversions.
3248 rex = DefaultLvalueConversion(rex.take());
3249 if (rex.isInvalid()) return QualType();
3251 const char *OpSpelling = isIndirect ? "->*" : ".*";
3252 // C++ 5.5p2
3253 // The binary operator .* [p3: ->*] binds its second operand, which shall
3254 // be of type "pointer to member of T" (where T is a completely-defined
3255 // class type) [...]
3256 QualType RType = rex.get()->getType();
3257 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
3258 if (!MemPtr) {
3259 Diag(Loc, diag::err_bad_memptr_rhs)
3260 << OpSpelling << RType << rex.get()->getSourceRange();
3261 return QualType();
3264 QualType Class(MemPtr->getClass(), 0);
3266 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3267 // member pointer points must be completely-defined. However, there is no
3268 // reason for this semantic distinction, and the rule is not enforced by
3269 // other compilers. Therefore, we do not check this property, as it is
3270 // likely to be considered a defect.
3272 // C++ 5.5p2
3273 // [...] to its first operand, which shall be of class T or of a class of
3274 // which T is an unambiguous and accessible base class. [p3: a pointer to
3275 // such a class]
3276 QualType LType = lex.get()->getType();
3277 if (isIndirect) {
3278 if (const PointerType *Ptr = LType->getAs<PointerType>())
3279 LType = Ptr->getPointeeType();
3280 else {
3281 Diag(Loc, diag::err_bad_memptr_lhs)
3282 << OpSpelling << 1 << LType
3283 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
3284 return QualType();
3288 if (!Context.hasSameUnqualifiedType(Class, LType)) {
3289 // If we want to check the hierarchy, we need a complete type.
3290 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
3291 << OpSpelling << (int)isIndirect)) {
3292 return QualType();
3294 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3295 /*DetectVirtual=*/false);
3296 // FIXME: Would it be useful to print full ambiguity paths, or is that
3297 // overkill?
3298 if (!IsDerivedFrom(LType, Class, Paths) ||
3299 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3300 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
3301 << (int)isIndirect << lex.get()->getType();
3302 return QualType();
3304 // Cast LHS to type of use.
3305 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
3306 ExprValueKind VK =
3307 isIndirect ? VK_RValue : CastCategory(lex.get());
3309 CXXCastPath BasePath;
3310 BuildBasePathArray(Paths, BasePath);
3311 lex = ImpCastExprToType(lex.take(), UseType, CK_DerivedToBase, VK, &BasePath);
3314 if (isa<CXXScalarValueInitExpr>(rex.get()->IgnoreParens())) {
3315 // Diagnose use of pointer-to-member type which when used as
3316 // the functional cast in a pointer-to-member expression.
3317 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3318 return QualType();
3321 // C++ 5.5p2
3322 // The result is an object or a function of the type specified by the
3323 // second operand.
3324 // The cv qualifiers are the union of those in the pointer and the left side,
3325 // in accordance with 5.5p5 and 5.2.5.
3326 QualType Result = MemPtr->getPointeeType();
3327 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
3329 // C++0x [expr.mptr.oper]p6:
3330 // In a .* expression whose object expression is an rvalue, the program is
3331 // ill-formed if the second operand is a pointer to member function with
3332 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3333 // expression is an lvalue, the program is ill-formed if the second operand
3334 // is a pointer to member function with ref-qualifier &&.
3335 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3336 switch (Proto->getRefQualifier()) {
3337 case RQ_None:
3338 // Do nothing
3339 break;
3341 case RQ_LValue:
3342 if (!isIndirect && !lex.get()->Classify(Context).isLValue())
3343 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3344 << RType << 1 << lex.get()->getSourceRange();
3345 break;
3347 case RQ_RValue:
3348 if (isIndirect || !lex.get()->Classify(Context).isRValue())
3349 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3350 << RType << 0 << lex.get()->getSourceRange();
3351 break;
3355 // C++ [expr.mptr.oper]p6:
3356 // The result of a .* expression whose second operand is a pointer
3357 // to a data member is of the same value category as its
3358 // first operand. The result of a .* expression whose second
3359 // operand is a pointer to a member function is a prvalue. The
3360 // result of an ->* expression is an lvalue if its second operand
3361 // is a pointer to data member and a prvalue otherwise.
3362 if (Result->isFunctionType()) {
3363 VK = VK_RValue;
3364 return Context.BoundMemberTy;
3365 } else if (isIndirect) {
3366 VK = VK_LValue;
3367 } else {
3368 VK = lex.get()->getValueKind();
3371 return Result;
3374 /// \brief Try to convert a type to another according to C++0x 5.16p3.
3376 /// This is part of the parameter validation for the ? operator. If either
3377 /// value operand is a class type, the two operands are attempted to be
3378 /// converted to each other. This function does the conversion in one direction.
3379 /// It returns true if the program is ill-formed and has already been diagnosed
3380 /// as such.
3381 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3382 SourceLocation QuestionLoc,
3383 bool &HaveConversion,
3384 QualType &ToType) {
3385 HaveConversion = false;
3386 ToType = To->getType();
3388 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
3389 SourceLocation());
3390 // C++0x 5.16p3
3391 // The process for determining whether an operand expression E1 of type T1
3392 // can be converted to match an operand expression E2 of type T2 is defined
3393 // as follows:
3394 // -- If E2 is an lvalue:
3395 bool ToIsLvalue = To->isLValue();
3396 if (ToIsLvalue) {
3397 // E1 can be converted to match E2 if E1 can be implicitly converted to
3398 // type "lvalue reference to T2", subject to the constraint that in the
3399 // conversion the reference must bind directly to E1.
3400 QualType T = Self.Context.getLValueReferenceType(ToType);
3401 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3403 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3404 if (InitSeq.isDirectReferenceBinding()) {
3405 ToType = T;
3406 HaveConversion = true;
3407 return false;
3410 if (InitSeq.isAmbiguous())
3411 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3414 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3415 // -- if E1 and E2 have class type, and the underlying class types are
3416 // the same or one is a base class of the other:
3417 QualType FTy = From->getType();
3418 QualType TTy = To->getType();
3419 const RecordType *FRec = FTy->getAs<RecordType>();
3420 const RecordType *TRec = TTy->getAs<RecordType>();
3421 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
3422 Self.IsDerivedFrom(FTy, TTy);
3423 if (FRec && TRec &&
3424 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
3425 // E1 can be converted to match E2 if the class of T2 is the
3426 // same type as, or a base class of, the class of T1, and
3427 // [cv2 > cv1].
3428 if (FRec == TRec || FDerivedFromT) {
3429 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
3430 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3431 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3432 if (InitSeq) {
3433 HaveConversion = true;
3434 return false;
3437 if (InitSeq.isAmbiguous())
3438 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3442 return false;
3445 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3446 // implicitly converted to the type that expression E2 would have
3447 // if E2 were converted to an rvalue (or the type it has, if E2 is
3448 // an rvalue).
3450 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3451 // to the array-to-pointer or function-to-pointer conversions.
3452 if (!TTy->getAs<TagType>())
3453 TTy = TTy.getUnqualifiedType();
3455 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3456 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3457 HaveConversion = !InitSeq.Failed();
3458 ToType = TTy;
3459 if (InitSeq.isAmbiguous())
3460 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3462 return false;
3465 /// \brief Try to find a common type for two according to C++0x 5.16p5.
3467 /// This is part of the parameter validation for the ? operator. If either
3468 /// value operand is a class type, overload resolution is used to find a
3469 /// conversion to a common type.
3470 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
3471 SourceLocation QuestionLoc) {
3472 Expr *Args[2] = { LHS.get(), RHS.get() };
3473 OverloadCandidateSet CandidateSet(QuestionLoc);
3474 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3475 CandidateSet);
3477 OverloadCandidateSet::iterator Best;
3478 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
3479 case OR_Success: {
3480 // We found a match. Perform the conversions on the arguments and move on.
3481 ExprResult LHSRes =
3482 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3483 Best->Conversions[0], Sema::AA_Converting);
3484 if (LHSRes.isInvalid())
3485 break;
3486 LHS = move(LHSRes);
3488 ExprResult RHSRes =
3489 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3490 Best->Conversions[1], Sema::AA_Converting);
3491 if (RHSRes.isInvalid())
3492 break;
3493 RHS = move(RHSRes);
3494 if (Best->Function)
3495 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
3496 return false;
3499 case OR_No_Viable_Function:
3501 // Emit a better diagnostic if one of the expressions is a null pointer
3502 // constant and the other is a pointer type. In this case, the user most
3503 // likely forgot to take the address of the other expression.
3504 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3505 return true;
3507 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3508 << LHS.get()->getType() << RHS.get()->getType()
3509 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3510 return true;
3512 case OR_Ambiguous:
3513 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
3514 << LHS.get()->getType() << RHS.get()->getType()
3515 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3516 // FIXME: Print the possible common types by printing the return types of
3517 // the viable candidates.
3518 break;
3520 case OR_Deleted:
3521 assert(false && "Conditional operator has only built-in overloads");
3522 break;
3524 return true;
3527 /// \brief Perform an "extended" implicit conversion as returned by
3528 /// TryClassUnification.
3529 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
3530 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3531 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
3532 SourceLocation());
3533 Expr *Arg = E.take();
3534 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3535 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
3536 if (Result.isInvalid())
3537 return true;
3539 E = Result;
3540 return false;
3543 /// \brief Check the operands of ?: under C++ semantics.
3545 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3546 /// extension. In this case, LHS == Cond. (But they're not aliases.)
3547 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
3548 ExprValueKind &VK, ExprObjectKind &OK,
3549 SourceLocation QuestionLoc) {
3550 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3551 // interface pointers.
3553 // C++0x 5.16p1
3554 // The first expression is contextually converted to bool.
3555 if (!Cond.get()->isTypeDependent()) {
3556 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3557 if (CondRes.isInvalid())
3558 return QualType();
3559 Cond = move(CondRes);
3562 // Assume r-value.
3563 VK = VK_RValue;
3564 OK = OK_Ordinary;
3566 // Either of the arguments dependent?
3567 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
3568 return Context.DependentTy;
3570 // C++0x 5.16p2
3571 // If either the second or the third operand has type (cv) void, ...
3572 QualType LTy = LHS.get()->getType();
3573 QualType RTy = RHS.get()->getType();
3574 bool LVoid = LTy->isVoidType();
3575 bool RVoid = RTy->isVoidType();
3576 if (LVoid || RVoid) {
3577 // ... then the [l2r] conversions are performed on the second and third
3578 // operands ...
3579 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3580 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3581 if (LHS.isInvalid() || RHS.isInvalid())
3582 return QualType();
3583 LTy = LHS.get()->getType();
3584 RTy = RHS.get()->getType();
3586 // ... and one of the following shall hold:
3587 // -- The second or the third operand (but not both) is a throw-
3588 // expression; the result is of the type of the other and is an rvalue.
3589 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3590 bool RThrow = isa<CXXThrowExpr>(RHS.get());
3591 if (LThrow && !RThrow)
3592 return RTy;
3593 if (RThrow && !LThrow)
3594 return LTy;
3596 // -- Both the second and third operands have type void; the result is of
3597 // type void and is an rvalue.
3598 if (LVoid && RVoid)
3599 return Context.VoidTy;
3601 // Neither holds, error.
3602 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3603 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3604 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3605 return QualType();
3608 // Neither is void.
3610 // C++0x 5.16p3
3611 // Otherwise, if the second and third operand have different types, and
3612 // either has (cv) class type, and attempt is made to convert each of those
3613 // operands to the other.
3614 if (!Context.hasSameType(LTy, RTy) &&
3615 (LTy->isRecordType() || RTy->isRecordType())) {
3616 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3617 // These return true if a single direction is already ambiguous.
3618 QualType L2RType, R2LType;
3619 bool HaveL2R, HaveR2L;
3620 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
3621 return QualType();
3622 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
3623 return QualType();
3625 // If both can be converted, [...] the program is ill-formed.
3626 if (HaveL2R && HaveR2L) {
3627 Diag(QuestionLoc, diag::err_conditional_ambiguous)
3628 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3629 return QualType();
3632 // If exactly one conversion is possible, that conversion is applied to
3633 // the chosen operand and the converted operands are used in place of the
3634 // original operands for the remainder of this section.
3635 if (HaveL2R) {
3636 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
3637 return QualType();
3638 LTy = LHS.get()->getType();
3639 } else if (HaveR2L) {
3640 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
3641 return QualType();
3642 RTy = RHS.get()->getType();
3646 // C++0x 5.16p4
3647 // If the second and third operands are glvalues of the same value
3648 // category and have the same type, the result is of that type and
3649 // value category and it is a bit-field if the second or the third
3650 // operand is a bit-field, or if both are bit-fields.
3651 // We only extend this to bitfields, not to the crazy other kinds of
3652 // l-values.
3653 bool Same = Context.hasSameType(LTy, RTy);
3654 if (Same &&
3655 LHS.get()->isGLValue() &&
3656 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3657 LHS.get()->isOrdinaryOrBitFieldObject() &&
3658 RHS.get()->isOrdinaryOrBitFieldObject()) {
3659 VK = LHS.get()->getValueKind();
3660 if (LHS.get()->getObjectKind() == OK_BitField ||
3661 RHS.get()->getObjectKind() == OK_BitField)
3662 OK = OK_BitField;
3663 return LTy;
3666 // C++0x 5.16p5
3667 // Otherwise, the result is an rvalue. If the second and third operands
3668 // do not have the same type, and either has (cv) class type, ...
3669 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3670 // ... overload resolution is used to determine the conversions (if any)
3671 // to be applied to the operands. If the overload resolution fails, the
3672 // program is ill-formed.
3673 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3674 return QualType();
3677 // C++0x 5.16p6
3678 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3679 // conversions are performed on the second and third operands.
3680 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3681 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3682 if (LHS.isInvalid() || RHS.isInvalid())
3683 return QualType();
3684 LTy = LHS.get()->getType();
3685 RTy = RHS.get()->getType();
3687 // After those conversions, one of the following shall hold:
3688 // -- The second and third operands have the same type; the result
3689 // is of that type. If the operands have class type, the result
3690 // is a prvalue temporary of the result type, which is
3691 // copy-initialized from either the second operand or the third
3692 // operand depending on the value of the first operand.
3693 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3694 if (LTy->isRecordType()) {
3695 // The operands have class type. Make a temporary copy.
3696 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
3697 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3698 SourceLocation(),
3699 LHS);
3700 if (LHSCopy.isInvalid())
3701 return QualType();
3703 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3704 SourceLocation(),
3705 RHS);
3706 if (RHSCopy.isInvalid())
3707 return QualType();
3709 LHS = LHSCopy;
3710 RHS = RHSCopy;
3713 return LTy;
3716 // Extension: conditional operator involving vector types.
3717 if (LTy->isVectorType() || RTy->isVectorType())
3718 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
3720 // -- The second and third operands have arithmetic or enumeration type;
3721 // the usual arithmetic conversions are performed to bring them to a
3722 // common type, and the result is of that type.
3723 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3724 UsualArithmeticConversions(LHS, RHS);
3725 if (LHS.isInvalid() || RHS.isInvalid())
3726 return QualType();
3727 return LHS.get()->getType();
3730 // -- The second and third operands have pointer type, or one has pointer
3731 // type and the other is a null pointer constant; pointer conversions
3732 // and qualification conversions are performed to bring them to their
3733 // composite pointer type. The result is of the composite pointer type.
3734 // -- The second and third operands have pointer to member type, or one has
3735 // pointer to member type and the other is a null pointer constant;
3736 // pointer to member conversions and qualification conversions are
3737 // performed to bring them to a common type, whose cv-qualification
3738 // shall match the cv-qualification of either the second or the third
3739 // operand. The result is of the common type.
3740 bool NonStandardCompositeType = false;
3741 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
3742 isSFINAEContext()? 0 : &NonStandardCompositeType);
3743 if (!Composite.isNull()) {
3744 if (NonStandardCompositeType)
3745 Diag(QuestionLoc,
3746 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3747 << LTy << RTy << Composite
3748 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3750 return Composite;
3753 // Similarly, attempt to find composite type of two objective-c pointers.
3754 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3755 if (!Composite.isNull())
3756 return Composite;
3758 // Check if we are using a null with a non-pointer type.
3759 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3760 return QualType();
3762 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3763 << LHS.get()->getType() << RHS.get()->getType()
3764 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3765 return QualType();
3768 /// \brief Find a merged pointer type and convert the two expressions to it.
3770 /// This finds the composite pointer type (or member pointer type) for @p E1
3771 /// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3772 /// type and returns it.
3773 /// It does not emit diagnostics.
3775 /// \param Loc The location of the operator requiring these two expressions to
3776 /// be converted to the composite pointer type.
3778 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3779 /// a non-standard (but still sane) composite type to which both expressions
3780 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3781 /// will be set true.
3782 QualType Sema::FindCompositePointerType(SourceLocation Loc,
3783 Expr *&E1, Expr *&E2,
3784 bool *NonStandardCompositeType) {
3785 if (NonStandardCompositeType)
3786 *NonStandardCompositeType = false;
3788 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3789 QualType T1 = E1->getType(), T2 = E2->getType();
3791 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3792 !T2->isAnyPointerType() && !T2->isMemberPointerType())
3793 return QualType();
3795 // C++0x 5.9p2
3796 // Pointer conversions and qualification conversions are performed on
3797 // pointer operands to bring them to their composite pointer type. If
3798 // one operand is a null pointer constant, the composite pointer type is
3799 // the type of the other operand.
3800 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3801 if (T2->isMemberPointerType())
3802 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
3803 else
3804 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
3805 return T2;
3807 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3808 if (T1->isMemberPointerType())
3809 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
3810 else
3811 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
3812 return T1;
3815 // Now both have to be pointers or member pointers.
3816 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3817 (!T2->isPointerType() && !T2->isMemberPointerType()))
3818 return QualType();
3820 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3821 // the other has type "pointer to cv2 T" and the composite pointer type is
3822 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3823 // Otherwise, the composite pointer type is a pointer type similar to the
3824 // type of one of the operands, with a cv-qualification signature that is
3825 // the union of the cv-qualification signatures of the operand types.
3826 // In practice, the first part here is redundant; it's subsumed by the second.
3827 // What we do here is, we build the two possible composite types, and try the
3828 // conversions in both directions. If only one works, or if the two composite
3829 // types are the same, we have succeeded.
3830 // FIXME: extended qualifiers?
3831 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3832 QualifierVector QualifierUnion;
3833 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3834 ContainingClassVector;
3835 ContainingClassVector MemberOfClass;
3836 QualType Composite1 = Context.getCanonicalType(T1),
3837 Composite2 = Context.getCanonicalType(T2);
3838 unsigned NeedConstBefore = 0;
3839 do {
3840 const PointerType *Ptr1, *Ptr2;
3841 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3842 (Ptr2 = Composite2->getAs<PointerType>())) {
3843 Composite1 = Ptr1->getPointeeType();
3844 Composite2 = Ptr2->getPointeeType();
3846 // If we're allowed to create a non-standard composite type, keep track
3847 // of where we need to fill in additional 'const' qualifiers.
3848 if (NonStandardCompositeType &&
3849 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3850 NeedConstBefore = QualifierUnion.size();
3852 QualifierUnion.push_back(
3853 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3854 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3855 continue;
3858 const MemberPointerType *MemPtr1, *MemPtr2;
3859 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3860 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3861 Composite1 = MemPtr1->getPointeeType();
3862 Composite2 = MemPtr2->getPointeeType();
3864 // If we're allowed to create a non-standard composite type, keep track
3865 // of where we need to fill in additional 'const' qualifiers.
3866 if (NonStandardCompositeType &&
3867 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3868 NeedConstBefore = QualifierUnion.size();
3870 QualifierUnion.push_back(
3871 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3872 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3873 MemPtr2->getClass()));
3874 continue;
3877 // FIXME: block pointer types?
3879 // Cannot unwrap any more types.
3880 break;
3881 } while (true);
3883 if (NeedConstBefore && NonStandardCompositeType) {
3884 // Extension: Add 'const' to qualifiers that come before the first qualifier
3885 // mismatch, so that our (non-standard!) composite type meets the
3886 // requirements of C++ [conv.qual]p4 bullet 3.
3887 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3888 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3889 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3890 *NonStandardCompositeType = true;
3895 // Rewrap the composites as pointers or member pointers with the union CVRs.
3896 ContainingClassVector::reverse_iterator MOC
3897 = MemberOfClass.rbegin();
3898 for (QualifierVector::reverse_iterator
3899 I = QualifierUnion.rbegin(),
3900 E = QualifierUnion.rend();
3901 I != E; (void)++I, ++MOC) {
3902 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
3903 if (MOC->first && MOC->second) {
3904 // Rebuild member pointer type
3905 Composite1 = Context.getMemberPointerType(
3906 Context.getQualifiedType(Composite1, Quals),
3907 MOC->first);
3908 Composite2 = Context.getMemberPointerType(
3909 Context.getQualifiedType(Composite2, Quals),
3910 MOC->second);
3911 } else {
3912 // Rebuild pointer type
3913 Composite1
3914 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3915 Composite2
3916 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
3920 // Try to convert to the first composite pointer type.
3921 InitializedEntity Entity1
3922 = InitializedEntity::InitializeTemporary(Composite1);
3923 InitializationKind Kind
3924 = InitializationKind::CreateCopy(Loc, SourceLocation());
3925 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3926 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
3928 if (E1ToC1 && E2ToC1) {
3929 // Conversion to Composite1 is viable.
3930 if (!Context.hasSameType(Composite1, Composite2)) {
3931 // Composite2 is a different type from Composite1. Check whether
3932 // Composite2 is also viable.
3933 InitializedEntity Entity2
3934 = InitializedEntity::InitializeTemporary(Composite2);
3935 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3936 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3937 if (E1ToC2 && E2ToC2) {
3938 // Both Composite1 and Composite2 are viable and are different;
3939 // this is an ambiguity.
3940 return QualType();
3944 // Convert E1 to Composite1
3945 ExprResult E1Result
3946 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
3947 if (E1Result.isInvalid())
3948 return QualType();
3949 E1 = E1Result.takeAs<Expr>();
3951 // Convert E2 to Composite1
3952 ExprResult E2Result
3953 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
3954 if (E2Result.isInvalid())
3955 return QualType();
3956 E2 = E2Result.takeAs<Expr>();
3958 return Composite1;
3961 // Check whether Composite2 is viable.
3962 InitializedEntity Entity2
3963 = InitializedEntity::InitializeTemporary(Composite2);
3964 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3965 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3966 if (!E1ToC2 || !E2ToC2)
3967 return QualType();
3969 // Convert E1 to Composite2
3970 ExprResult E1Result
3971 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
3972 if (E1Result.isInvalid())
3973 return QualType();
3974 E1 = E1Result.takeAs<Expr>();
3976 // Convert E2 to Composite2
3977 ExprResult E2Result
3978 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
3979 if (E2Result.isInvalid())
3980 return QualType();
3981 E2 = E2Result.takeAs<Expr>();
3983 return Composite2;
3986 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
3987 if (!E)
3988 return ExprError();
3990 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3992 // If the result is a glvalue, we shouldn't bind it.
3993 if (!E->isRValue())
3994 return Owned(E);
3996 // In ARC, calls that return a retainable type can return retained,
3997 // in which case we have to insert a consuming cast.
3998 if (getLangOptions().ObjCAutoRefCount &&
3999 E->getType()->isObjCRetainableType()) {
4001 bool ReturnsRetained;
4003 // For actual calls, we compute this by examining the type of the
4004 // called value.
4005 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4006 Expr *Callee = Call->getCallee()->IgnoreParens();
4007 QualType T = Callee->getType();
4009 if (T == Context.BoundMemberTy) {
4010 // Handle pointer-to-members.
4011 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4012 T = BinOp->getRHS()->getType();
4013 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4014 T = Mem->getMemberDecl()->getType();
4017 if (const PointerType *Ptr = T->getAs<PointerType>())
4018 T = Ptr->getPointeeType();
4019 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4020 T = Ptr->getPointeeType();
4021 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4022 T = MemPtr->getPointeeType();
4024 const FunctionType *FTy = T->getAs<FunctionType>();
4025 assert(FTy && "call to value not of function type?");
4026 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4028 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4029 // type always produce a +1 object.
4030 } else if (isa<StmtExpr>(E)) {
4031 ReturnsRetained = true;
4033 // For message sends and property references, we try to find an
4034 // actual method. FIXME: we should infer retention by selector in
4035 // cases where we don't have an actual method.
4036 } else {
4037 Decl *D = 0;
4038 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4039 D = Send->getMethodDecl();
4040 } else {
4041 CastExpr *CE = cast<CastExpr>(E);
4042 // FIXME. What other cast kinds to check for?
4043 if (CE->getCastKind() == CK_ObjCProduceObject ||
4044 CE->getCastKind() == CK_LValueToRValue)
4045 return MaybeBindToTemporary(CE->getSubExpr());
4046 assert(CE->getCastKind() == CK_GetObjCProperty);
4047 const ObjCPropertyRefExpr *PRE = CE->getSubExpr()->getObjCProperty();
4048 D = (PRE->isImplicitProperty() ? PRE->getImplicitPropertyGetter() : 0);
4051 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
4054 ExprNeedsCleanups = true;
4056 CastKind ck = (ReturnsRetained ? CK_ObjCConsumeObject
4057 : CK_ObjCReclaimReturnedObject);
4058 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4059 VK_RValue));
4062 if (!getLangOptions().CPlusPlus)
4063 return Owned(E);
4065 const RecordType *RT = E->getType()->getAs<RecordType>();
4066 if (!RT)
4067 return Owned(E);
4069 // That should be enough to guarantee that this type is complete.
4070 // If it has a trivial destructor, we can avoid the extra copy.
4071 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4072 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
4073 return Owned(E);
4075 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4077 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4078 if (Destructor) {
4079 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
4080 CheckDestructorAccess(E->getExprLoc(), Destructor,
4081 PDiag(diag::err_access_dtor_temp)
4082 << E->getType());
4084 ExprTemporaries.push_back(Temp);
4085 ExprNeedsCleanups = true;
4087 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4090 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4091 assert(SubExpr && "sub expression can't be null!");
4093 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
4094 assert(ExprTemporaries.size() >= FirstTemporary);
4095 assert(ExprNeedsCleanups || ExprTemporaries.size() == FirstTemporary);
4096 if (!ExprNeedsCleanups)
4097 return SubExpr;
4099 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
4100 ExprTemporaries.begin() + FirstTemporary,
4101 ExprTemporaries.size() - FirstTemporary);
4102 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
4103 ExprTemporaries.end());
4104 ExprNeedsCleanups = false;
4106 return E;
4109 ExprResult
4110 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
4111 if (SubExpr.isInvalid())
4112 return ExprError();
4114 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
4117 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
4118 assert(SubStmt && "sub statement can't be null!");
4120 if (!ExprNeedsCleanups)
4121 return SubStmt;
4123 // FIXME: In order to attach the temporaries, wrap the statement into
4124 // a StmtExpr; currently this is only used for asm statements.
4125 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4126 // a new AsmStmtWithTemporaries.
4127 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4128 SourceLocation(),
4129 SourceLocation());
4130 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4131 SourceLocation());
4132 return MaybeCreateExprWithCleanups(E);
4135 ExprResult
4136 Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
4137 tok::TokenKind OpKind, ParsedType &ObjectType,
4138 bool &MayBePseudoDestructor) {
4139 // Since this might be a postfix expression, get rid of ParenListExprs.
4140 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
4141 if (Result.isInvalid()) return ExprError();
4142 Base = Result.get();
4144 QualType BaseType = Base->getType();
4145 MayBePseudoDestructor = false;
4146 if (BaseType->isDependentType()) {
4147 // If we have a pointer to a dependent type and are using the -> operator,
4148 // the object type is the type that the pointer points to. We might still
4149 // have enough information about that type to do something useful.
4150 if (OpKind == tok::arrow)
4151 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4152 BaseType = Ptr->getPointeeType();
4154 ObjectType = ParsedType::make(BaseType);
4155 MayBePseudoDestructor = true;
4156 return Owned(Base);
4159 // C++ [over.match.oper]p8:
4160 // [...] When operator->returns, the operator-> is applied to the value
4161 // returned, with the original second operand.
4162 if (OpKind == tok::arrow) {
4163 // The set of types we've considered so far.
4164 llvm::SmallPtrSet<CanQualType,8> CTypes;
4165 llvm::SmallVector<SourceLocation, 8> Locations;
4166 CTypes.insert(Context.getCanonicalType(BaseType));
4168 while (BaseType->isRecordType()) {
4169 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4170 if (Result.isInvalid())
4171 return ExprError();
4172 Base = Result.get();
4173 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
4174 Locations.push_back(OpCall->getDirectCallee()->getLocation());
4175 BaseType = Base->getType();
4176 CanQualType CBaseType = Context.getCanonicalType(BaseType);
4177 if (!CTypes.insert(CBaseType)) {
4178 Diag(OpLoc, diag::err_operator_arrow_circular);
4179 for (unsigned i = 0; i < Locations.size(); i++)
4180 Diag(Locations[i], diag::note_declared_at);
4181 return ExprError();
4185 if (BaseType->isPointerType())
4186 BaseType = BaseType->getPointeeType();
4189 // We could end up with various non-record types here, such as extended
4190 // vector types or Objective-C interfaces. Just return early and let
4191 // ActOnMemberReferenceExpr do the work.
4192 if (!BaseType->isRecordType()) {
4193 // C++ [basic.lookup.classref]p2:
4194 // [...] If the type of the object expression is of pointer to scalar
4195 // type, the unqualified-id is looked up in the context of the complete
4196 // postfix-expression.
4198 // This also indicates that we should be parsing a
4199 // pseudo-destructor-name.
4200 ObjectType = ParsedType();
4201 MayBePseudoDestructor = true;
4202 return Owned(Base);
4205 // The object type must be complete (or dependent).
4206 if (!BaseType->isDependentType() &&
4207 RequireCompleteType(OpLoc, BaseType,
4208 PDiag(diag::err_incomplete_member_access)))
4209 return ExprError();
4211 // C++ [basic.lookup.classref]p2:
4212 // If the id-expression in a class member access (5.2.5) is an
4213 // unqualified-id, and the type of the object expression is of a class
4214 // type C (or of pointer to a class type C), the unqualified-id is looked
4215 // up in the scope of class C. [...]
4216 ObjectType = ParsedType::make(BaseType);
4217 return move(Base);
4220 ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
4221 Expr *MemExpr) {
4222 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
4223 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4224 << isa<CXXPseudoDestructorExpr>(MemExpr)
4225 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
4227 return ActOnCallExpr(/*Scope*/ 0,
4228 MemExpr,
4229 /*LPLoc*/ ExpectedLParenLoc,
4230 MultiExprArg(),
4231 /*RPLoc*/ ExpectedLParenLoc);
4234 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
4235 SourceLocation OpLoc,
4236 tok::TokenKind OpKind,
4237 const CXXScopeSpec &SS,
4238 TypeSourceInfo *ScopeTypeInfo,
4239 SourceLocation CCLoc,
4240 SourceLocation TildeLoc,
4241 PseudoDestructorTypeStorage Destructed,
4242 bool HasTrailingLParen) {
4243 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
4245 // C++ [expr.pseudo]p2:
4246 // The left-hand side of the dot operator shall be of scalar type. The
4247 // left-hand side of the arrow operator shall be of pointer to scalar type.
4248 // This scalar type is the object type.
4249 QualType ObjectType = Base->getType();
4250 if (OpKind == tok::arrow) {
4251 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4252 ObjectType = Ptr->getPointeeType();
4253 } else if (!Base->isTypeDependent()) {
4254 // The user wrote "p->" when she probably meant "p."; fix it.
4255 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4256 << ObjectType << true
4257 << FixItHint::CreateReplacement(OpLoc, ".");
4258 if (isSFINAEContext())
4259 return ExprError();
4261 OpKind = tok::period;
4265 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4266 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4267 << ObjectType << Base->getSourceRange();
4268 return ExprError();
4271 // C++ [expr.pseudo]p2:
4272 // [...] The cv-unqualified versions of the object type and of the type
4273 // designated by the pseudo-destructor-name shall be the same type.
4274 if (DestructedTypeInfo) {
4275 QualType DestructedType = DestructedTypeInfo->getType();
4276 SourceLocation DestructedTypeStart
4277 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
4278 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4279 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4280 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4281 << ObjectType << DestructedType << Base->getSourceRange()
4282 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4284 // Recover by setting the destructed type to the object type.
4285 DestructedType = ObjectType;
4286 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4287 DestructedTypeStart);
4288 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4289 } else if (DestructedType.getObjCLifetime() !=
4290 ObjectType.getObjCLifetime()) {
4292 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4293 // Okay: just pretend that the user provided the correctly-qualified
4294 // type.
4295 } else {
4296 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4297 << ObjectType << DestructedType << Base->getSourceRange()
4298 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4301 // Recover by setting the destructed type to the object type.
4302 DestructedType = ObjectType;
4303 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4304 DestructedTypeStart);
4305 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4310 // C++ [expr.pseudo]p2:
4311 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4312 // form
4314 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
4316 // shall designate the same scalar type.
4317 if (ScopeTypeInfo) {
4318 QualType ScopeType = ScopeTypeInfo->getType();
4319 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
4320 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
4322 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
4323 diag::err_pseudo_dtor_type_mismatch)
4324 << ObjectType << ScopeType << Base->getSourceRange()
4325 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
4327 ScopeType = QualType();
4328 ScopeTypeInfo = 0;
4332 Expr *Result
4333 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4334 OpKind == tok::arrow, OpLoc,
4335 SS.getWithLocInContext(Context),
4336 ScopeTypeInfo,
4337 CCLoc,
4338 TildeLoc,
4339 Destructed);
4341 if (HasTrailingLParen)
4342 return Owned(Result);
4344 return DiagnoseDtorReference(Destructed.getLocation(), Result);
4347 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4348 SourceLocation OpLoc,
4349 tok::TokenKind OpKind,
4350 CXXScopeSpec &SS,
4351 UnqualifiedId &FirstTypeName,
4352 SourceLocation CCLoc,
4353 SourceLocation TildeLoc,
4354 UnqualifiedId &SecondTypeName,
4355 bool HasTrailingLParen) {
4356 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4357 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4358 "Invalid first type name in pseudo-destructor");
4359 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4360 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4361 "Invalid second type name in pseudo-destructor");
4363 // C++ [expr.pseudo]p2:
4364 // The left-hand side of the dot operator shall be of scalar type. The
4365 // left-hand side of the arrow operator shall be of pointer to scalar type.
4366 // This scalar type is the object type.
4367 QualType ObjectType = Base->getType();
4368 if (OpKind == tok::arrow) {
4369 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4370 ObjectType = Ptr->getPointeeType();
4371 } else if (!ObjectType->isDependentType()) {
4372 // The user wrote "p->" when she probably meant "p."; fix it.
4373 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4374 << ObjectType << true
4375 << FixItHint::CreateReplacement(OpLoc, ".");
4376 if (isSFINAEContext())
4377 return ExprError();
4379 OpKind = tok::period;
4383 // Compute the object type that we should use for name lookup purposes. Only
4384 // record types and dependent types matter.
4385 ParsedType ObjectTypePtrForLookup;
4386 if (!SS.isSet()) {
4387 if (ObjectType->isRecordType())
4388 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
4389 else if (ObjectType->isDependentType())
4390 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
4393 // Convert the name of the type being destructed (following the ~) into a
4394 // type (with source-location information).
4395 QualType DestructedType;
4396 TypeSourceInfo *DestructedTypeInfo = 0;
4397 PseudoDestructorTypeStorage Destructed;
4398 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
4399 ParsedType T = getTypeName(*SecondTypeName.Identifier,
4400 SecondTypeName.StartLocation,
4401 S, &SS, true, false, ObjectTypePtrForLookup);
4402 if (!T &&
4403 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4404 (!SS.isSet() && ObjectType->isDependentType()))) {
4405 // The name of the type being destroyed is a dependent name, and we
4406 // couldn't find anything useful in scope. Just store the identifier and
4407 // it's location, and we'll perform (qualified) name lookup again at
4408 // template instantiation time.
4409 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4410 SecondTypeName.StartLocation);
4411 } else if (!T) {
4412 Diag(SecondTypeName.StartLocation,
4413 diag::err_pseudo_dtor_destructor_non_type)
4414 << SecondTypeName.Identifier << ObjectType;
4415 if (isSFINAEContext())
4416 return ExprError();
4418 // Recover by assuming we had the right type all along.
4419 DestructedType = ObjectType;
4420 } else
4421 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
4422 } else {
4423 // Resolve the template-id to a type.
4424 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
4425 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4426 TemplateId->getTemplateArgs(),
4427 TemplateId->NumArgs);
4428 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4429 TemplateId->Template,
4430 TemplateId->TemplateNameLoc,
4431 TemplateId->LAngleLoc,
4432 TemplateArgsPtr,
4433 TemplateId->RAngleLoc);
4434 if (T.isInvalid() || !T.get()) {
4435 // Recover by assuming we had the right type all along.
4436 DestructedType = ObjectType;
4437 } else
4438 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
4441 // If we've performed some kind of recovery, (re-)build the type source
4442 // information.
4443 if (!DestructedType.isNull()) {
4444 if (!DestructedTypeInfo)
4445 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
4446 SecondTypeName.StartLocation);
4447 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4450 // Convert the name of the scope type (the type prior to '::') into a type.
4451 TypeSourceInfo *ScopeTypeInfo = 0;
4452 QualType ScopeType;
4453 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4454 FirstTypeName.Identifier) {
4455 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
4456 ParsedType T = getTypeName(*FirstTypeName.Identifier,
4457 FirstTypeName.StartLocation,
4458 S, &SS, true, false, ObjectTypePtrForLookup);
4459 if (!T) {
4460 Diag(FirstTypeName.StartLocation,
4461 diag::err_pseudo_dtor_destructor_non_type)
4462 << FirstTypeName.Identifier << ObjectType;
4464 if (isSFINAEContext())
4465 return ExprError();
4467 // Just drop this type. It's unnecessary anyway.
4468 ScopeType = QualType();
4469 } else
4470 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
4471 } else {
4472 // Resolve the template-id to a type.
4473 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
4474 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4475 TemplateId->getTemplateArgs(),
4476 TemplateId->NumArgs);
4477 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4478 TemplateId->Template,
4479 TemplateId->TemplateNameLoc,
4480 TemplateId->LAngleLoc,
4481 TemplateArgsPtr,
4482 TemplateId->RAngleLoc);
4483 if (T.isInvalid() || !T.get()) {
4484 // Recover by dropping this type.
4485 ScopeType = QualType();
4486 } else
4487 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
4491 if (!ScopeType.isNull() && !ScopeTypeInfo)
4492 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4493 FirstTypeName.StartLocation);
4496 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
4497 ScopeTypeInfo, CCLoc, TildeLoc,
4498 Destructed, HasTrailingLParen);
4501 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
4502 CXXMethodDecl *Method) {
4503 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4504 FoundDecl, Method);
4505 if (Exp.isInvalid())
4506 return true;
4508 MemberExpr *ME =
4509 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
4510 SourceLocation(), Method->getType(),
4511 VK_RValue, OK_Ordinary);
4512 QualType ResultType = Method->getResultType();
4513 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4514 ResultType = ResultType.getNonLValueExprType(Context);
4516 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
4517 CXXMemberCallExpr *CE =
4518 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
4519 Exp.get()->getLocEnd());
4520 return CE;
4523 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4524 SourceLocation RParen) {
4525 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4526 Operand->CanThrow(Context),
4527 KeyLoc, RParen));
4530 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4531 Expr *Operand, SourceLocation RParen) {
4532 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
4535 /// Perform the conversions required for an expression used in a
4536 /// context that ignores the result.
4537 ExprResult Sema::IgnoredValueConversions(Expr *E) {
4538 // C99 6.3.2.1:
4539 // [Except in specific positions,] an lvalue that does not have
4540 // array type is converted to the value stored in the
4541 // designated object (and is no longer an lvalue).
4542 if (E->isRValue()) {
4543 // In C, function designators (i.e. expressions of function type)
4544 // are r-values, but we still want to do function-to-pointer decay
4545 // on them. This is both technically correct and convenient for
4546 // some clients.
4547 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4548 return DefaultFunctionArrayConversion(E);
4550 return Owned(E);
4553 // We always want to do this on ObjC property references.
4554 if (E->getObjectKind() == OK_ObjCProperty) {
4555 ExprResult Res = ConvertPropertyForRValue(E);
4556 if (Res.isInvalid()) return Owned(E);
4557 E = Res.take();
4558 if (E->isRValue()) return Owned(E);
4561 // Otherwise, this rule does not apply in C++, at least not for the moment.
4562 if (getLangOptions().CPlusPlus) return Owned(E);
4564 // GCC seems to also exclude expressions of incomplete enum type.
4565 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4566 if (!T->getDecl()->isComplete()) {
4567 // FIXME: stupid workaround for a codegen bug!
4568 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4569 return Owned(E);
4573 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4574 if (Res.isInvalid())
4575 return Owned(E);
4576 E = Res.take();
4578 if (!E->getType()->isVoidType())
4579 RequireCompleteType(E->getExprLoc(), E->getType(),
4580 diag::err_incomplete_type);
4581 return Owned(E);
4584 ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4585 ExprResult FullExpr = Owned(FE);
4587 if (!FullExpr.get())
4588 return ExprError();
4590 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
4591 return ExprError();
4593 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4594 if (FullExpr.isInvalid())
4595 return ExprError();
4597 FullExpr = IgnoredValueConversions(FullExpr.take());
4598 if (FullExpr.isInvalid())
4599 return ExprError();
4601 CheckImplicitConversions(FullExpr.get());
4602 return MaybeCreateExprWithCleanups(FullExpr);
4605 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4606 if (!FullStmt) return StmtError();
4608 return MaybeCreateStmtWithCleanups(FullStmt);
4611 bool Sema::CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS,
4612 UnqualifiedId &Name) {
4613 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4614 DeclarationName TargetName = TargetNameInfo.getName();
4615 if (!TargetName)
4616 return false;
4618 // Do the redeclaration lookup in the current scope.
4619 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4620 Sema::NotForRedeclaration);
4621 R.suppressDiagnostics();
4622 LookupParsedName(R, getCurScope(), &SS);
4623 return !R.empty();