clang API Documentation

SemaExprCXX.cpp

Go to the documentation of this file.
00001 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for C++ expressions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "Sema.h"
00015 #include "SemaInit.h"
00016 #include "Lookup.h"
00017 #include "clang/AST/ASTContext.h"
00018 #include "clang/AST/CXXInheritance.h"
00019 #include "clang/AST/ExprCXX.h"
00020 #include "clang/AST/TypeLoc.h"
00021 #include "clang/Basic/PartialDiagnostic.h"
00022 #include "clang/Basic/TargetInfo.h"
00023 #include "clang/Lex/Preprocessor.h"
00024 #include "clang/Parse/DeclSpec.h"
00025 #include "clang/Parse/Template.h"
00026 #include "llvm/ADT/STLExtras.h"
00027 using namespace clang;
00028 
00029 Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
00030                                         IdentifierInfo &II, 
00031                                         SourceLocation NameLoc,
00032                                         Scope *S, const CXXScopeSpec &SS,
00033                                         TypeTy *ObjectTypePtr,
00034                                         bool EnteringContext) {
00035   // Determine where to perform name lookup.
00036 
00037   // FIXME: This area of the standard is very messy, and the current
00038   // wording is rather unclear about which scopes we search for the
00039   // destructor name; see core issues 399 and 555. Issue 399 in
00040   // particular shows where the current description of destructor name
00041   // lookup is completely out of line with existing practice, e.g.,
00042   // this appears to be ill-formed:
00043   //
00044   //   namespace N {
00045   //     template <typename T> struct S {
00046   //       ~S();
00047   //     };
00048   //   }
00049   //
00050   //   void f(N::S<int>* s) {
00051   //     s->N::S<int>::~S();
00052   //   }
00053   //
00054   // See also PR6358 and PR6359.
00055   QualType SearchType;
00056   DeclContext *LookupCtx = 0;
00057   bool isDependent = false;
00058   bool LookInScope = false;
00059 
00060   // If we have an object type, it's because we are in a
00061   // pseudo-destructor-expression or a member access expression, and
00062   // we know what type we're looking for.
00063   if (ObjectTypePtr)
00064     SearchType = GetTypeFromParser(ObjectTypePtr);
00065 
00066   if (SS.isSet()) {
00067     NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
00068     
00069     bool AlreadySearched = false;
00070     bool LookAtPrefix = true;
00071     if (!getLangOptions().CPlusPlus0x) {
00072       // C++ [basic.lookup.qual]p6:
00073       //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, 
00074       //   the type-names are looked up as types in the scope designated by the
00075       //   nested-name-specifier. In a qualified-id of the form:
00076       // 
00077       //     ::[opt] nested-name-specifier  ̃ class-name 
00078       //
00079       //   where the nested-name-specifier designates a namespace scope, and in
00080       //   a qualified-id of the form:
00081       //
00082       //     ::opt nested-name-specifier class-name ::  ̃ class-name 
00083       //
00084       //   the class-names are looked up as types in the scope designated by 
00085       //   the nested-name-specifier.
00086       //
00087       // Here, we check the first case (completely) and determine whether the
00088       // code below is permitted to look at the prefix of the 
00089       // nested-name-specifier (as we do in C++0x).
00090       DeclContext *DC = computeDeclContext(SS, EnteringContext);
00091       if (DC && DC->isFileContext()) {
00092         AlreadySearched = true;
00093         LookupCtx = DC;
00094         isDependent = false;
00095       } else if (DC && isa<CXXRecordDecl>(DC))
00096         LookAtPrefix = false;
00097     }
00098     
00099     // C++0x [basic.lookup.qual]p6:
00100     //   If a pseudo-destructor-name (5.2.4) contains a
00101     //   nested-name-specifier, the type-names are looked up as types
00102     //   in the scope designated by the nested-name-specifier. Similarly, in 
00103     //   a qualified-id of the form:
00104     //
00105     //     :: [opt] nested-name-specifier[opt] class-name :: ~class-name 
00106     //
00107     //   the second class-name is looked up in the same scope as the first.
00108     //
00109     // To implement this, we look at the prefix of the
00110     // nested-name-specifier we were given, and determine the lookup
00111     // context from that.
00112     //
00113     // We also fold in the second case from the C++03 rules quoted further 
00114     // above.
00115     NestedNameSpecifier *Prefix = 0;
00116     if (AlreadySearched) {
00117       // Nothing left to do.
00118     } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
00119       CXXScopeSpec PrefixSS;
00120       PrefixSS.setScopeRep(Prefix);
00121       LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
00122       isDependent = isDependentScopeSpecifier(PrefixSS);
00123     } else if (getLangOptions().CPlusPlus0x &&
00124                (LookupCtx = computeDeclContext(SS, EnteringContext))) {
00125       if (!LookupCtx->isTranslationUnit())
00126         LookupCtx = LookupCtx->getParent();
00127       isDependent = LookupCtx && LookupCtx->isDependentContext();
00128     } else if (ObjectTypePtr) {
00129       LookupCtx = computeDeclContext(SearchType);
00130       isDependent = SearchType->isDependentType();
00131     } else {
00132       LookupCtx = computeDeclContext(SS, EnteringContext);
00133       isDependent = LookupCtx && LookupCtx->isDependentContext();
00134     }
00135     
00136     LookInScope = false;
00137   } else if (ObjectTypePtr) {
00138     // C++ [basic.lookup.classref]p3:
00139     //   If the unqualified-id is ~type-name, the type-name is looked up
00140     //   in the context of the entire postfix-expression. If the type T
00141     //   of the object expression is of a class type C, the type-name is
00142     //   also looked up in the scope of class C. At least one of the
00143     //   lookups shall find a name that refers to (possibly
00144     //   cv-qualified) T.
00145     LookupCtx = computeDeclContext(SearchType);
00146     isDependent = SearchType->isDependentType();
00147     assert((isDependent || !SearchType->isIncompleteType()) && 
00148            "Caller should have completed object type");
00149 
00150     LookInScope = true;
00151   } else {
00152     // Perform lookup into the current scope (only).
00153     LookInScope = true;
00154   }
00155 
00156   LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
00157   for (unsigned Step = 0; Step != 2; ++Step) {
00158     // Look for the name first in the computed lookup context (if we
00159     // have one) and, if that fails to find a match, in the sope (if
00160     // we're allowed to look there).
00161     Found.clear();
00162     if (Step == 0 && LookupCtx)
00163       LookupQualifiedName(Found, LookupCtx);
00164     else if (Step == 1 && LookInScope && S)
00165       LookupName(Found, S);
00166     else
00167       continue;
00168 
00169     // FIXME: Should we be suppressing ambiguities here?
00170     if (Found.isAmbiguous())
00171       return 0;
00172 
00173     if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
00174       QualType T = Context.getTypeDeclType(Type);
00175       // If we found the injected-class-name of a class template, retrieve the
00176       // type of that template.
00177       // FIXME: We really shouldn't need to do this.
00178       if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Type))
00179         if (Record->isInjectedClassName())
00180           if (Record->getDescribedClassTemplate())
00181             T = Record->getDescribedClassTemplate()
00182                                            ->getInjectedClassNameType(Context);
00183 
00184       if (SearchType.isNull() || SearchType->isDependentType() ||
00185           Context.hasSameUnqualifiedType(T, SearchType)) {
00186         // We found our type!
00187 
00188         return T.getAsOpaquePtr();
00189       }
00190     }
00191 
00192     // If the name that we found is a class template name, and it is
00193     // the same name as the template name in the last part of the
00194     // nested-name-specifier (if present) or the object type, then
00195     // this is the destructor for that class.
00196     // FIXME: This is a workaround until we get real drafting for core
00197     // issue 399, for which there isn't even an obvious direction. 
00198     if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
00199       QualType MemberOfType;
00200       if (SS.isSet()) {
00201         if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
00202           // Figure out the type of the context, if it has one.
00203           if (ClassTemplateSpecializationDecl *Spec
00204                           = dyn_cast<ClassTemplateSpecializationDecl>(Ctx))
00205             MemberOfType = Context.getTypeDeclType(Spec);
00206           else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
00207             if (Record->getDescribedClassTemplate())
00208               MemberOfType = Record->getDescribedClassTemplate()
00209                                           ->getInjectedClassNameType(Context);
00210             else
00211               MemberOfType = Context.getTypeDeclType(Record);
00212           }
00213         }
00214       }
00215       if (MemberOfType.isNull())
00216         MemberOfType = SearchType;
00217       
00218       if (MemberOfType.isNull())
00219         continue;
00220 
00221       // We're referring into a class template specialization. If the
00222       // class template we found is the same as the template being
00223       // specialized, we found what we are looking for.
00224       if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
00225         if (ClassTemplateSpecializationDecl *Spec
00226               = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
00227           if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
00228                 Template->getCanonicalDecl())
00229             return MemberOfType.getAsOpaquePtr();
00230         }
00231 
00232         continue;
00233       }
00234       
00235       // We're referring to an unresolved class template
00236       // specialization. Determine whether we class template we found
00237       // is the same as the template being specialized or, if we don't
00238       // know which template is being specialized, that it at least
00239       // has the same name.
00240       if (const TemplateSpecializationType *SpecType
00241             = MemberOfType->getAs<TemplateSpecializationType>()) {
00242         TemplateName SpecName = SpecType->getTemplateName();
00243 
00244         // The class template we found is the same template being
00245         // specialized.
00246         if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
00247           if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
00248             return MemberOfType.getAsOpaquePtr();
00249 
00250           continue;
00251         }
00252 
00253         // The class template we found has the same name as the
00254         // (dependent) template name being specialized.
00255         if (DependentTemplateName *DepTemplate 
00256                                     = SpecName.getAsDependentTemplateName()) {
00257           if (DepTemplate->isIdentifier() &&
00258               DepTemplate->getIdentifier() == Template->getIdentifier())
00259             return MemberOfType.getAsOpaquePtr();
00260 
00261           continue;
00262         }
00263       }
00264     }
00265   }
00266 
00267   if (isDependent) {
00268     // We didn't find our type, but that's okay: it's dependent
00269     // anyway.
00270     NestedNameSpecifier *NNS = 0;
00271     SourceRange Range;
00272     if (SS.isSet()) {
00273       NNS = (NestedNameSpecifier *)SS.getScopeRep();
00274       Range = SourceRange(SS.getRange().getBegin(), NameLoc);
00275     } else {
00276       NNS = NestedNameSpecifier::Create(Context, &II);
00277       Range = SourceRange(NameLoc);
00278     }
00279 
00280     return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
00281   }
00282 
00283   if (ObjectTypePtr)
00284     Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
00285       << &II;        
00286   else
00287     Diag(NameLoc, diag::err_destructor_class_name);
00288 
00289   return 0;
00290 }
00291 
00292 /// ActOnCXXTypeidOfType - Parse typeid( type-id ).
00293 Action::OwningExprResult
00294 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
00295                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
00296   if (!StdNamespace)
00297     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
00298 
00299   if (isType) {
00300     // C++ [expr.typeid]p4:
00301     //   The top-level cv-qualifiers of the lvalue expression or the type-id 
00302     //   that is the operand of typeid are always ignored.
00303     // FIXME: Preserve type source info.
00304     // FIXME: Preserve the type before we stripped the cv-qualifiers?
00305     QualType T = GetTypeFromParser(TyOrExpr);
00306     if (T.isNull())
00307       return ExprError();
00308     
00309     // C++ [expr.typeid]p4:
00310     //   If the type of the type-id is a class type or a reference to a class 
00311     //   type, the class shall be completely-defined.
00312     QualType CheckT = T;
00313     if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
00314       CheckT = RefType->getPointeeType();
00315     
00316     if (CheckT->getAs<RecordType>() &&
00317         RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
00318       return ExprError();
00319     
00320     TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
00321   }
00322 
00323   IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
00324   LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
00325   LookupQualifiedName(R, StdNamespace);
00326   RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
00327   if (!TypeInfoRecordDecl)
00328     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
00329 
00330   QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
00331 
00332   if (!isType) {
00333     bool isUnevaluatedOperand = true;
00334     Expr *E = static_cast<Expr *>(TyOrExpr);
00335     if (E && !E->isTypeDependent()) {
00336       QualType T = E->getType();
00337       if (const RecordType *RecordT = T->getAs<RecordType>()) {
00338         CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
00339         // C++ [expr.typeid]p3:
00340         //   [...] If the type of the expression is a class type, the class
00341         //   shall be completely-defined.
00342         if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
00343           return ExprError();
00344 
00345         // C++ [expr.typeid]p3:
00346         //   When typeid is applied to an expression other than an lvalue of a
00347         //   polymorphic class type [...] [the] expression is an unevaluated
00348         //   operand. [...]
00349         if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
00350           isUnevaluatedOperand = false;
00351       }
00352 
00353       // C++ [expr.typeid]p4:
00354       //   [...] If the type of the type-id is a reference to a possibly
00355       //   cv-qualified type, the result of the typeid expression refers to a 
00356       //   std::type_info object representing the cv-unqualified referenced 
00357       //   type.
00358       if (T.hasQualifiers()) {
00359         ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
00360                           E->isLvalue(Context));
00361         TyOrExpr = E;
00362       }
00363     }
00364 
00365     // If this is an unevaluated operand, clear out the set of
00366     // declaration references we have been computing and eliminate any
00367     // temporaries introduced in its computation.
00368     if (isUnevaluatedOperand)
00369       ExprEvalContexts.back().Context = Unevaluated;
00370   }
00371 
00372   return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
00373                                            TypeInfoType.withConst(),
00374                                            SourceRange(OpLoc, RParenLoc)));
00375 }
00376 
00377 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
00378 Action::OwningExprResult
00379 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
00380   assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
00381          "Unknown C++ Boolean value!");
00382   return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
00383                                                 Context.BoolTy, OpLoc));
00384 }
00385 
00386 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
00387 Action::OwningExprResult
00388 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
00389   return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
00390 }
00391 
00392 /// ActOnCXXThrow - Parse throw expressions.
00393 Action::OwningExprResult
00394 Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
00395   Expr *Ex = E.takeAs<Expr>();
00396   if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
00397     return ExprError();
00398   return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
00399 }
00400 
00401 /// CheckCXXThrowOperand - Validate the operand of a throw.
00402 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
00403   // C++ [except.throw]p3:
00404   //   A throw-expression initializes a temporary object, called the exception
00405   //   object, the type of which is determined by removing any top-level
00406   //   cv-qualifiers from the static type of the operand of throw and adjusting
00407   //   the type from "array of T" or "function returning T" to "pointer to T" 
00408   //   or "pointer to function returning T", [...]
00409   if (E->getType().hasQualifiers())
00410     ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
00411                       E->isLvalue(Context) == Expr::LV_Valid);
00412   
00413   DefaultFunctionArrayConversion(E);
00414 
00415   //   If the type of the exception would be an incomplete type or a pointer
00416   //   to an incomplete type other than (cv) void the program is ill-formed.
00417   QualType Ty = E->getType();
00418   int isPointer = 0;
00419   if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
00420     Ty = Ptr->getPointeeType();
00421     isPointer = 1;
00422   }
00423   if (!isPointer || !Ty->isVoidType()) {
00424     if (RequireCompleteType(ThrowLoc, Ty,
00425                             PDiag(isPointer ? diag::err_throw_incomplete_ptr
00426                                             : diag::err_throw_incomplete)
00427                               << E->getSourceRange()))
00428       return true;
00429 
00430     // FIXME: This is just a hack to mark the copy constructor referenced.
00431     // This should go away when the next FIXME is fixed.
00432     const RecordType *RT = Ty->getAs<RecordType>();
00433     if (!RT)
00434       return false;
00435 
00436     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
00437     if (RD->hasTrivialCopyConstructor())
00438       return false;
00439     CXXConstructorDecl *CopyCtor = RD->getCopyConstructor(Context, 0);
00440     MarkDeclarationReferenced(ThrowLoc, CopyCtor);
00441   }
00442 
00443   // FIXME: Construct a temporary here.
00444   return false;
00445 }
00446 
00447 Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
00448   /// C++ 9.3.2: In the body of a non-static member function, the keyword this
00449   /// is a non-lvalue expression whose value is the address of the object for
00450   /// which the function is called.
00451 
00452   if (!isa<FunctionDecl>(CurContext))
00453     return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
00454 
00455   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
00456     if (MD->isInstance())
00457       return Owned(new (Context) CXXThisExpr(ThisLoc,
00458                                              MD->getThisType(Context),
00459                                              /*isImplicit=*/false));
00460 
00461   return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
00462 }
00463 
00464 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
00465 /// Can be interpreted either as function-style casting ("int(x)")
00466 /// or class type construction ("ClassType(x,y,z)")
00467 /// or creation of a value-initialized type ("int()").
00468 Action::OwningExprResult
00469 Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
00470                                 SourceLocation LParenLoc,
00471                                 MultiExprArg exprs,
00472                                 SourceLocation *CommaLocs,
00473                                 SourceLocation RParenLoc) {
00474   if (!TypeRep)
00475     return ExprError();
00476 
00477   TypeSourceInfo *TInfo;
00478   QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
00479   if (!TInfo)
00480     TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
00481   unsigned NumExprs = exprs.size();
00482   Expr **Exprs = (Expr**)exprs.get();
00483   SourceLocation TyBeginLoc = TypeRange.getBegin();
00484   SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
00485 
00486   if (Ty->isDependentType() ||
00487       CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
00488     exprs.release();
00489 
00490     return Owned(CXXUnresolvedConstructExpr::Create(Context,
00491                                                     TypeRange.getBegin(), Ty,
00492                                                     LParenLoc,
00493                                                     Exprs, NumExprs,
00494                                                     RParenLoc));
00495   }
00496 
00497   if (Ty->isArrayType())
00498     return ExprError(Diag(TyBeginLoc,
00499                           diag::err_value_init_for_array_type) << FullRange);
00500   if (!Ty->isVoidType() &&
00501       RequireCompleteType(TyBeginLoc, Ty,
00502                           PDiag(diag::err_invalid_incomplete_type_use)
00503                             << FullRange))
00504     return ExprError();
00505   
00506   if (RequireNonAbstractType(TyBeginLoc, Ty,
00507                              diag::err_allocation_of_abstract_type))
00508     return ExprError();
00509 
00510 
00511   // C++ [expr.type.conv]p1:
00512   // If the expression list is a single expression, the type conversion
00513   // expression is equivalent (in definedness, and if defined in meaning) to the
00514   // corresponding cast expression.
00515   //
00516   if (NumExprs == 1) {
00517     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
00518     CXXMethodDecl *Method = 0;
00519     if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
00520                        /*FunctionalStyle=*/true))
00521       return ExprError();
00522 
00523     exprs.release();
00524     if (Method) {
00525       OwningExprResult CastArg 
00526         = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(), 
00527                                Kind, Method, Owned(Exprs[0]));
00528       if (CastArg.isInvalid())
00529         return ExprError();
00530 
00531       Exprs[0] = CastArg.takeAs<Expr>();
00532     }
00533 
00534     return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
00535                                                      TInfo, TyBeginLoc, Kind,
00536                                                      Exprs[0], RParenLoc));
00537   }
00538 
00539   if (const RecordType *RT = Ty->getAs<RecordType>()) {
00540     CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
00541 
00542     if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
00543         !Record->hasTrivialDestructor()) {
00544       InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
00545       InitializationKind Kind
00546         = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(), 
00547                                                       LParenLoc, RParenLoc)
00548                    : InitializationKind::CreateValue(TypeRange.getBegin(), 
00549                                                      LParenLoc, RParenLoc);
00550       InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
00551       OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
00552                                                 move(exprs));
00553 
00554       // FIXME: Improve AST representation?
00555       return move(Result);
00556     }
00557 
00558     // Fall through to value-initialize an object of class type that
00559     // doesn't have a user-declared default constructor.
00560   }
00561 
00562   // C++ [expr.type.conv]p1:
00563   // If the expression list specifies more than a single value, the type shall
00564   // be a class with a suitably declared constructor.
00565   //
00566   if (NumExprs > 1)
00567     return ExprError(Diag(CommaLocs[0],
00568                           diag::err_builtin_func_cast_more_than_one_arg)
00569       << FullRange);
00570 
00571   assert(NumExprs == 0 && "Expected 0 expressions");
00572   // C++ [expr.type.conv]p2:
00573   // The expression T(), where T is a simple-type-specifier for a non-array
00574   // complete object type or the (possibly cv-qualified) void type, creates an
00575   // rvalue of the specified type, which is value-initialized.
00576   //
00577   exprs.release();
00578   return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
00579 }
00580 
00581 
00582 /// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
00583 /// @code new (memory) int[size][4] @endcode
00584 /// or
00585 /// @code ::new Foo(23, "hello") @endcode
00586 /// For the interpretation of this heap of arguments, consult the base version.
00587 Action::OwningExprResult
00588 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
00589                   SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
00590                   SourceLocation PlacementRParen, bool ParenTypeId,
00591                   Declarator &D, SourceLocation ConstructorLParen,
00592                   MultiExprArg ConstructorArgs,
00593                   SourceLocation ConstructorRParen) {
00594   Expr *ArraySize = 0;
00595   // If the specified type is an array, unwrap it and save the expression.
00596   if (D.getNumTypeObjects() > 0 &&
00597       D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
00598     DeclaratorChunk &Chunk = D.getTypeObject(0);
00599     if (Chunk.Arr.hasStatic)
00600       return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
00601         << D.getSourceRange());
00602     if (!Chunk.Arr.NumElts)
00603       return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
00604         << D.getSourceRange());
00605 
00606     if (ParenTypeId) {
00607       // Can't have dynamic array size when the type-id is in parentheses.
00608       Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
00609       if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
00610           !NumElts->isIntegerConstantExpr(Context)) {
00611         Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
00612           << NumElts->getSourceRange();
00613         return ExprError();
00614       }
00615     }
00616 
00617     ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
00618     D.DropFirstTypeObject();
00619   }
00620 
00621   // Every dimension shall be of constant size.
00622   if (ArraySize) {
00623     for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
00624       if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
00625         break;
00626 
00627       DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
00628       if (Expr *NumElts = (Expr *)Array.NumElts) {
00629         if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
00630             !NumElts->isIntegerConstantExpr(Context)) {
00631           Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
00632             << NumElts->getSourceRange();
00633           return ExprError();
00634         }
00635       }
00636     }
00637   }
00638 
00639   //FIXME: Store TypeSourceInfo in CXXNew expression.
00640   TypeSourceInfo *TInfo = 0;
00641   QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
00642   if (D.isInvalidType())
00643     return ExprError();
00644     
00645   return BuildCXXNew(StartLoc, UseGlobal,
00646                      PlacementLParen,
00647                      move(PlacementArgs),
00648                      PlacementRParen,
00649                      ParenTypeId,
00650                      AllocType,
00651                      D.getSourceRange().getBegin(),
00652                      D.getSourceRange(),
00653                      Owned(ArraySize),
00654                      ConstructorLParen,
00655                      move(ConstructorArgs),
00656                      ConstructorRParen);
00657 }
00658 
00659 Sema::OwningExprResult
00660 Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
00661                   SourceLocation PlacementLParen,
00662                   MultiExprArg PlacementArgs,
00663                   SourceLocation PlacementRParen,
00664                   bool ParenTypeId,
00665                   QualType AllocType,
00666                   SourceLocation TypeLoc,
00667                   SourceRange TypeRange,
00668                   ExprArg ArraySizeE,
00669                   SourceLocation ConstructorLParen,
00670                   MultiExprArg ConstructorArgs,
00671                   SourceLocation ConstructorRParen) {
00672   if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
00673     return ExprError();
00674 
00675   QualType ResultType = Context.getPointerType(AllocType);
00676 
00677   // That every array dimension except the first is constant was already
00678   // checked by the type check above.
00679 
00680   // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
00681   //   or enumeration type with a non-negative value."
00682   Expr *ArraySize = (Expr *)ArraySizeE.get();
00683   if (ArraySize && !ArraySize->isTypeDependent()) {
00684     QualType SizeType = ArraySize->getType();
00685     if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
00686       return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
00687                             diag::err_array_size_not_integral)
00688         << SizeType << ArraySize->getSourceRange());
00689     // Let's see if this is a constant < 0. If so, we reject it out of hand.
00690     // We don't care about special rules, so we tell the machinery it's not
00691     // evaluated - it gives us a result in more cases.
00692     if (!ArraySize->isValueDependent()) {
00693       llvm::APSInt Value;
00694       if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
00695         if (Value < llvm::APSInt(
00696                         llvm::APInt::getNullValue(Value.getBitWidth()), 
00697                                  Value.isUnsigned()))
00698           return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
00699                            diag::err_typecheck_negative_array_size)
00700             << ArraySize->getSourceRange());
00701       }
00702     }
00703     
00704     ImpCastExprToType(ArraySize, Context.getSizeType(),
00705                       CastExpr::CK_IntegralCast);
00706   }
00707 
00708   FunctionDecl *OperatorNew = 0;
00709   FunctionDecl *OperatorDelete = 0;
00710   Expr **PlaceArgs = (Expr**)PlacementArgs.get();
00711   unsigned NumPlaceArgs = PlacementArgs.size();
00712   
00713   if (!AllocType->isDependentType() &&
00714       !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
00715       FindAllocationFunctions(StartLoc,
00716                               SourceRange(PlacementLParen, PlacementRParen),
00717                               UseGlobal, AllocType, ArraySize, PlaceArgs,
00718                               NumPlaceArgs, OperatorNew, OperatorDelete))
00719     return ExprError();
00720   llvm::SmallVector<Expr *, 8> AllPlaceArgs;
00721   if (OperatorNew) {
00722     // Add default arguments, if any.
00723     const FunctionProtoType *Proto = 
00724       OperatorNew->getType()->getAs<FunctionProtoType>();
00725     VariadicCallType CallType = 
00726       Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
00727     bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
00728                                           Proto, 1, PlaceArgs, NumPlaceArgs, 
00729                                           AllPlaceArgs, CallType);
00730     if (Invalid)
00731       return ExprError();
00732     
00733     NumPlaceArgs = AllPlaceArgs.size();
00734     if (NumPlaceArgs > 0)
00735       PlaceArgs = &AllPlaceArgs[0];
00736   }
00737   
00738   bool Init = ConstructorLParen.isValid();
00739   // --- Choosing a constructor ---
00740   CXXConstructorDecl *Constructor = 0;
00741   Expr **ConsArgs = (Expr**)ConstructorArgs.get();
00742   unsigned NumConsArgs = ConstructorArgs.size();
00743   ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
00744 
00745   if (!AllocType->isDependentType() &&
00746       !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
00747     // C++0x [expr.new]p15:
00748     //   A new-expression that creates an object of type T initializes that
00749     //   object as follows:
00750     InitializationKind Kind
00751     //     - If the new-initializer is omitted, the object is default-
00752     //       initialized (8.5); if no initialization is performed,
00753     //       the object has indeterminate value
00754       = !Init? InitializationKind::CreateDefault(TypeLoc)
00755     //     - Otherwise, the new-initializer is interpreted according to the 
00756     //       initialization rules of 8.5 for direct-initialization.
00757              : InitializationKind::CreateDirect(TypeLoc,
00758                                                 ConstructorLParen, 
00759                                                 ConstructorRParen);
00760     
00761     InitializedEntity Entity
00762       = InitializedEntity::InitializeNew(StartLoc, AllocType);
00763     InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
00764     OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 
00765                                                 move(ConstructorArgs));
00766     if (FullInit.isInvalid())
00767       return ExprError();
00768     
00769     // FullInit is our initializer; walk through it to determine if it's a 
00770     // constructor call, which CXXNewExpr handles directly.
00771     if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
00772       if (CXXBindTemporaryExpr *Binder
00773             = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
00774         FullInitExpr = Binder->getSubExpr();
00775       if (CXXConstructExpr *Construct
00776                     = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
00777         Constructor = Construct->getConstructor();
00778         for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
00779                                          AEnd = Construct->arg_end();
00780              A != AEnd; ++A)
00781           ConvertedConstructorArgs.push_back(A->Retain());
00782       } else {
00783         // Take the converted initializer.
00784         ConvertedConstructorArgs.push_back(FullInit.release());
00785       }
00786     } else {
00787       // No initialization required.
00788     }
00789     
00790     // Take the converted arguments and use them for the new expression.
00791     NumConsArgs = ConvertedConstructorArgs.size();
00792     ConsArgs = (Expr **)ConvertedConstructorArgs.take();
00793   }
00794   
00795   // Mark the new and delete operators as referenced.
00796   if (OperatorNew)
00797     MarkDeclarationReferenced(StartLoc, OperatorNew);
00798   if (OperatorDelete)
00799     MarkDeclarationReferenced(StartLoc, OperatorDelete);
00800 
00801   // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
00802   
00803   PlacementArgs.release();
00804   ConstructorArgs.release();
00805   ArraySizeE.release();
00806   return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
00807                                         PlaceArgs, NumPlaceArgs, ParenTypeId,
00808                                         ArraySize, Constructor, Init,
00809                                         ConsArgs, NumConsArgs, OperatorDelete,
00810                                         ResultType, StartLoc,
00811                                         Init ? ConstructorRParen :
00812                                                SourceLocation()));
00813 }
00814 
00815 /// CheckAllocatedType - Checks that a type is suitable as the allocated type
00816 /// in a new-expression.
00817 /// dimension off and stores the size expression in ArraySize.
00818 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
00819                               SourceRange R) {
00820   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
00821   //   abstract class type or array thereof.
00822   if (AllocType->isFunctionType())
00823     return Diag(Loc, diag::err_bad_new_type)
00824       << AllocType << 0 << R;
00825   else if (AllocType->isReferenceType())
00826     return Diag(Loc, diag::err_bad_new_type)
00827       << AllocType << 1 << R;
00828   else if (!AllocType->isDependentType() &&
00829            RequireCompleteType(Loc, AllocType,
00830                                PDiag(diag::err_new_incomplete_type)
00831                                  << R))
00832     return true;
00833   else if (RequireNonAbstractType(Loc, AllocType,
00834                                   diag::err_allocation_of_abstract_type))
00835     return true;
00836 
00837   return false;
00838 }
00839 
00840 /// \brief Determine whether the given function is a non-placement
00841 /// deallocation function.
00842 static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
00843   if (FD->isInvalidDecl())
00844     return false;
00845 
00846   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
00847     return Method->isUsualDeallocationFunction();
00848 
00849   return ((FD->getOverloadedOperator() == OO_Delete ||
00850            FD->getOverloadedOperator() == OO_Array_Delete) &&
00851           FD->getNumParams() == 1);
00852 }
00853 
00854 /// FindAllocationFunctions - Finds the overloads of operator new and delete
00855 /// that are appropriate for the allocation.
00856 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
00857                                    bool UseGlobal, QualType AllocType,
00858                                    bool IsArray, Expr **PlaceArgs,
00859                                    unsigned NumPlaceArgs,
00860                                    FunctionDecl *&OperatorNew,
00861                                    FunctionDecl *&OperatorDelete) {
00862   // --- Choosing an allocation function ---
00863   // C++ 5.3.4p8 - 14 & 18
00864   // 1) If UseGlobal is true, only look in the global scope. Else, also look
00865   //   in the scope of the allocated class.
00866   // 2) If an array size is given, look for operator new[], else look for
00867   //   operator new.
00868   // 3) The first argument is always size_t. Append the arguments from the
00869   //   placement form.
00870 
00871   llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
00872   // We don't care about the actual value of this argument.
00873   // FIXME: Should the Sema create the expression and embed it in the syntax
00874   // tree? Or should the consumer just recalculate the value?
00875   IntegerLiteral Size(llvm::APInt::getNullValue(
00876                       Context.Target.getPointerWidth(0)),
00877                       Context.getSizeType(),
00878                       SourceLocation());
00879   AllocArgs[0] = &Size;
00880   std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
00881 
00882   // C++ [expr.new]p8:
00883   //   If the allocated type is a non-array type, the allocation
00884   //   function’s name is operator new and the deallocation function’s
00885   //   name is operator delete. If the allocated type is an array
00886   //   type, the allocation function’s name is operator new[] and the
00887   //   deallocation function’s name is operator delete[].
00888   DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
00889                                         IsArray ? OO_Array_New : OO_New);
00890   DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
00891                                         IsArray ? OO_Array_Delete : OO_Delete);
00892 
00893   if (AllocType->isRecordType() && !UseGlobal) {
00894     CXXRecordDecl *Record
00895       = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
00896     if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
00897                           AllocArgs.size(), Record, /*AllowMissing=*/true,
00898                           OperatorNew))
00899       return true;
00900   }
00901   if (!OperatorNew) {
00902     // Didn't find a member overload. Look for a global one.
00903     DeclareGlobalNewDelete();
00904     DeclContext *TUDecl = Context.getTranslationUnitDecl();
00905     if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
00906                           AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
00907                           OperatorNew))
00908       return true;
00909   }
00910 
00911   // FindAllocationOverload can change the passed in arguments, so we need to
00912   // copy them back.
00913   if (NumPlaceArgs > 0)
00914     std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
00915 
00916   // C++ [expr.new]p19:
00917   //
00918   //   If the new-expression begins with a unary :: operator, the
00919   //   deallocation function’s name is looked up in the global
00920   //   scope. Otherwise, if the allocated type is a class type T or an
00921   //   array thereof, the deallocation function’s name is looked up in
00922   //   the scope of T. If this lookup fails to find the name, or if
00923   //   the allocated type is not a class type or array thereof, the
00924   //   deallocation function’s name is looked up in the global scope.
00925   LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
00926   if (AllocType->isRecordType() && !UseGlobal) {
00927     CXXRecordDecl *RD
00928       = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
00929     LookupQualifiedName(FoundDelete, RD);
00930   }
00931 
00932   if (FoundDelete.empty()) {
00933     DeclareGlobalNewDelete();
00934     LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
00935   }
00936 
00937   FoundDelete.suppressDiagnostics();
00938   llvm::SmallVector<NamedDecl *, 4> Matches;
00939   if (NumPlaceArgs > 1) {
00940     // C++ [expr.new]p20:
00941     //   A declaration of a placement deallocation function matches the
00942     //   declaration of a placement allocation function if it has the
00943     //   same number of parameters and, after parameter transformations
00944     //   (8.3.5), all parameter types except the first are
00945     //   identical. [...]
00946     // 
00947     // To perform this comparison, we compute the function type that
00948     // the deallocation function should have, and use that type both
00949     // for template argument deduction and for comparison purposes.
00950     QualType ExpectedFunctionType;
00951     {
00952       const FunctionProtoType *Proto
00953         = OperatorNew->getType()->getAs<FunctionProtoType>();
00954       llvm::SmallVector<QualType, 4> ArgTypes;
00955       ArgTypes.push_back(Context.VoidPtrTy); 
00956       for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
00957         ArgTypes.push_back(Proto->getArgType(I));
00958 
00959       ExpectedFunctionType
00960         = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
00961                                   ArgTypes.size(),
00962                                   Proto->isVariadic(),
00963                                   0, false, false, 0, 0, false, CC_Default);
00964     }
00965 
00966     for (LookupResult::iterator D = FoundDelete.begin(), 
00967                              DEnd = FoundDelete.end();
00968          D != DEnd; ++D) {
00969       FunctionDecl *Fn = 0;
00970       if (FunctionTemplateDecl *FnTmpl 
00971             = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
00972         // Perform template argument deduction to try to match the
00973         // expected function type.
00974         TemplateDeductionInfo Info(Context, StartLoc);
00975         if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
00976           continue;
00977       } else
00978         Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
00979 
00980       if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
00981         Matches.push_back(Fn);
00982     }
00983   } else {
00984     // C++ [expr.new]p20:
00985     //   [...] Any non-placement deallocation function matches a
00986     //   non-placement allocation function. [...]
00987     for (LookupResult::iterator D = FoundDelete.begin(), 
00988                              DEnd = FoundDelete.end();
00989          D != DEnd; ++D) {
00990       if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
00991         if (isNonPlacementDeallocationFunction(Fn))
00992           Matches.push_back(*D);
00993     }
00994   }
00995 
00996   // C++ [expr.new]p20:
00997   //   [...] If the lookup finds a single matching deallocation
00998   //   function, that function will be called; otherwise, no
00999   //   deallocation function will be called.
01000   if (Matches.size() == 1) {
01001     // FIXME: Drops access, using-declaration info!
01002     OperatorDelete = cast<FunctionDecl>(Matches[0]->getUnderlyingDecl());
01003 
01004     // C++0x [expr.new]p20:
01005     //   If the lookup finds the two-parameter form of a usual
01006     //   deallocation function (3.7.4.2) and that function, considered
01007     //   as a placement deallocation function, would have been
01008     //   selected as a match for the allocation function, the program
01009     //   is ill-formed.
01010     if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
01011         isNonPlacementDeallocationFunction(OperatorDelete)) {
01012       Diag(StartLoc, diag::err_placement_new_non_placement_delete)
01013         << SourceRange(PlaceArgs[0]->getLocStart(), 
01014                        PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
01015       Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
01016         << DeleteName;
01017     }
01018   }
01019 
01020   return false;
01021 }
01022 
01023 /// FindAllocationOverload - Find an fitting overload for the allocation
01024 /// function in the specified scope.
01025 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
01026                                   DeclarationName Name, Expr** Args,
01027                                   unsigned NumArgs, DeclContext *Ctx,
01028                                   bool AllowMissing, FunctionDecl *&Operator) {
01029   LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
01030   LookupQualifiedName(R, Ctx);
01031   if (R.empty()) {
01032     if (AllowMissing)
01033       return false;
01034     return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
01035       << Name << Range;
01036   }
01037 
01038   // FIXME: handle ambiguity
01039 
01040   OverloadCandidateSet Candidates(StartLoc);
01041   for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 
01042        Alloc != AllocEnd; ++Alloc) {
01043     // Even member operator new/delete are implicitly treated as
01044     // static, so don't use AddMemberCandidate.
01045 
01046     if (FunctionTemplateDecl *FnTemplate = 
01047           dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) {
01048       AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(),
01049                                    /*ExplicitTemplateArgs=*/0, Args, NumArgs,
01050                                    Candidates,
01051                                    /*SuppressUserConversions=*/false);
01052       continue;
01053     }
01054 
01055     FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl());
01056     AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
01057                          /*SuppressUserConversions=*/false);
01058   }
01059 
01060   // Do the resolution.
01061   OverloadCandidateSet::iterator Best;
01062   switch(BestViableFunction(Candidates, StartLoc, Best)) {
01063   case OR_Success: {
01064     // Got one!
01065     FunctionDecl *FnDecl = Best->Function;
01066     // The first argument is size_t, and the first parameter must be size_t,
01067     // too. This is checked on declaration and can be assumed. (It can't be
01068     // asserted on, though, since invalid decls are left in there.)
01069     // Whatch out for variadic allocator function.
01070     unsigned NumArgsInFnDecl = FnDecl->getNumParams();
01071     for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
01072       if (PerformCopyInitialization(Args[i],
01073                                     FnDecl->getParamDecl(i)->getType(),
01074                                     AA_Passing))
01075         return true;
01076     }
01077     Operator = FnDecl;
01078     return false;
01079   }
01080 
01081   case OR_No_Viable_Function:
01082     Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
01083       << Name << Range;
01084     PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
01085     return true;
01086 
01087   case OR_Ambiguous:
01088     Diag(StartLoc, diag::err_ovl_ambiguous_call)
01089       << Name << Range;
01090     PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
01091     return true;
01092 
01093   case OR_Deleted:
01094     Diag(StartLoc, diag::err_ovl_deleted_call)
01095       << Best->Function->isDeleted()
01096       << Name << Range;
01097     PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
01098     return true;
01099   }
01100   assert(false && "Unreachable, bad result from BestViableFunction");
01101   return true;
01102 }
01103 
01104 
01105 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
01106 /// delete. These are:
01107 /// @code
01108 ///   void* operator new(std::size_t) throw(std::bad_alloc);
01109 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
01110 ///   void operator delete(void *) throw();
01111 ///   void operator delete[](void *) throw();
01112 /// @endcode
01113 /// Note that the placement and nothrow forms of new are *not* implicitly
01114 /// declared. Their use requires including <new>.
01115 void Sema::DeclareGlobalNewDelete() {
01116   if (GlobalNewDeleteDeclared)
01117     return;
01118   
01119   // C++ [basic.std.dynamic]p2:
01120   //   [...] The following allocation and deallocation functions (18.4) are 
01121   //   implicitly declared in global scope in each translation unit of a 
01122   //   program
01123   //   
01124   //     void* operator new(std::size_t) throw(std::bad_alloc);
01125   //     void* operator new[](std::size_t) throw(std::bad_alloc); 
01126   //     void  operator delete(void*) throw(); 
01127   //     void  operator delete[](void*) throw();
01128   //
01129   //   These implicit declarations introduce only the function names operator 
01130   //   new, operator new[], operator delete, operator delete[].
01131   //
01132   // Here, we need to refer to std::bad_alloc, so we will implicitly declare
01133   // "std" or "bad_alloc" as necessary to form the exception specification.
01134   // However, we do not make these implicit declarations visible to name
01135   // lookup.
01136   if (!StdNamespace) {
01137     // The "std" namespace has not yet been defined, so build one implicitly.
01138     StdNamespace = NamespaceDecl::Create(Context, 
01139                                          Context.getTranslationUnitDecl(),
01140                                          SourceLocation(),
01141                                          &PP.getIdentifierTable().get("std"));
01142     StdNamespace->setImplicit(true);
01143   }
01144   
01145   if (!StdBadAlloc) {
01146     // The "std::bad_alloc" class has not yet been declared, so build it
01147     // implicitly.
01148     StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class, 
01149                                         StdNamespace, 
01150                                         SourceLocation(), 
01151                                       &PP.getIdentifierTable().get("bad_alloc"), 
01152                                         SourceLocation(), 0);
01153     StdBadAlloc->setImplicit(true);
01154   }
01155   
01156   GlobalNewDeleteDeclared = true;
01157 
01158   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
01159   QualType SizeT = Context.getSizeType();
01160   bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
01161 
01162   DeclareGlobalAllocationFunction(
01163       Context.DeclarationNames.getCXXOperatorName(OO_New),
01164       VoidPtr, SizeT, AssumeSaneOperatorNew);
01165   DeclareGlobalAllocationFunction(
01166       Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
01167       VoidPtr, SizeT, AssumeSaneOperatorNew);
01168   DeclareGlobalAllocationFunction(
01169       Context.DeclarationNames.getCXXOperatorName(OO_Delete),
01170       Context.VoidTy, VoidPtr);
01171   DeclareGlobalAllocationFunction(
01172       Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
01173       Context.VoidTy, VoidPtr);
01174 }
01175 
01176 /// DeclareGlobalAllocationFunction - Declares a single implicit global
01177 /// allocation function if it doesn't already exist.
01178 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
01179                                            QualType Return, QualType Argument,
01180                                            bool AddMallocAttr) {
01181   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
01182 
01183   // Check if this function is already declared.
01184   {
01185     DeclContext::lookup_iterator Alloc, AllocEnd;
01186     for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
01187          Alloc != AllocEnd; ++Alloc) {
01188       // Only look at non-template functions, as it is the predefined,
01189       // non-templated allocation function we are trying to declare here.
01190       if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
01191         QualType InitialParamType =
01192           Context.getCanonicalType(
01193             Func->getParamDecl(0)->getType().getUnqualifiedType());
01194         // FIXME: Do we need to check for default arguments here?
01195         if (Func->getNumParams() == 1 && InitialParamType == Argument)
01196           return;
01197       }
01198     }
01199   }
01200 
01201   QualType BadAllocType;
01202   bool HasBadAllocExceptionSpec 
01203     = (Name.getCXXOverloadedOperator() == OO_New ||
01204        Name.getCXXOverloadedOperator() == OO_Array_New);
01205   if (HasBadAllocExceptionSpec) {
01206     assert(StdBadAlloc && "Must have std::bad_alloc declared");
01207     BadAllocType = Context.getTypeDeclType(StdBadAlloc);
01208   }
01209   
01210   QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
01211                                             true, false,
01212                                             HasBadAllocExceptionSpec? 1 : 0,
01213                                             &BadAllocType, false, CC_Default);
01214   FunctionDecl *Alloc =
01215     FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
01216                          FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
01217   Alloc->setImplicit();
01218   
01219   if (AddMallocAttr)
01220     Alloc->addAttr(::new (Context) MallocAttr());
01221   
01222   ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
01223                                            0, Argument, /*TInfo=*/0,
01224                                            VarDecl::None, 0);
01225   Alloc->setParams(&Param, 1);
01226 
01227   // FIXME: Also add this declaration to the IdentifierResolver, but
01228   // make sure it is at the end of the chain to coincide with the
01229   // global scope.
01230   ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
01231 }
01232 
01233 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
01234                                     DeclarationName Name,
01235                                     FunctionDecl* &Operator) {
01236   LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
01237   // Try to find operator delete/operator delete[] in class scope.
01238   LookupQualifiedName(Found, RD);
01239   
01240   if (Found.isAmbiguous())
01241     return true;
01242 
01243   for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
01244        F != FEnd; ++F) {
01245     if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
01246       if (Delete->isUsualDeallocationFunction()) {
01247         Operator = Delete;
01248         return false;
01249       }
01250   }
01251 
01252   // We did find operator delete/operator delete[] declarations, but
01253   // none of them were suitable.
01254   if (!Found.empty()) {
01255     Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
01256       << Name << RD;
01257         
01258     for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
01259          F != FEnd; ++F) {
01260       Diag((*F)->getLocation(), 
01261            diag::note_delete_member_function_declared_here)
01262         << Name;
01263     }
01264 
01265     return true;
01266   }
01267 
01268   // Look for a global declaration.
01269   DeclareGlobalNewDelete();
01270   DeclContext *TUDecl = Context.getTranslationUnitDecl();
01271   
01272   CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
01273   Expr* DeallocArgs[1];
01274   DeallocArgs[0] = &Null;
01275   if (FindAllocationOverload(StartLoc, SourceRange(), Name,
01276                              DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
01277                              Operator))
01278     return true;
01279 
01280   assert(Operator && "Did not find a deallocation function!");
01281   return false;
01282 }
01283 
01284 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
01285 /// @code ::delete ptr; @endcode
01286 /// or
01287 /// @code delete [] ptr; @endcode
01288 Action::OwningExprResult
01289 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
01290                      bool ArrayForm, ExprArg Operand) {
01291   // C++ [expr.delete]p1:
01292   //   The operand shall have a pointer type, or a class type having a single
01293   //   conversion function to a pointer type. The result has type void.
01294   //
01295   // DR599 amends "pointer type" to "pointer to object type" in both cases.
01296 
01297   FunctionDecl *OperatorDelete = 0;
01298 
01299   Expr *Ex = (Expr *)Operand.get();
01300   if (!Ex->isTypeDependent()) {
01301     QualType Type = Ex->getType();
01302 
01303     if (const RecordType *Record = Type->getAs<RecordType>()) {
01304       llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
01305       CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
01306       const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
01307       
01308       for (UnresolvedSetImpl::iterator I = Conversions->begin(),
01309              E = Conversions->end(); I != E; ++I) {
01310         // Skip over templated conversion functions; they aren't considered.
01311         if (isa<FunctionTemplateDecl>(*I))
01312           continue;
01313         
01314         CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
01315         
01316         QualType ConvType = Conv->getConversionType().getNonReferenceType();
01317         if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
01318           if (ConvPtrType->getPointeeType()->isObjectType())
01319             ObjectPtrConversions.push_back(Conv);
01320       }
01321       if (ObjectPtrConversions.size() == 1) {
01322         // We have a single conversion to a pointer-to-object type. Perform
01323         // that conversion.
01324         Operand.release();
01325         if (!PerformImplicitConversion(Ex, 
01326                             ObjectPtrConversions.front()->getConversionType(), 
01327                                       AA_Converting)) {
01328           Operand = Owned(Ex);
01329           Type = Ex->getType();
01330         }
01331       }
01332       else if (ObjectPtrConversions.size() > 1) {
01333         Diag(StartLoc, diag::err_ambiguous_delete_operand)
01334               << Type << Ex->getSourceRange();
01335         for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
01336           CXXConversionDecl *Conv = ObjectPtrConversions[i];
01337           NoteOverloadCandidate(Conv);
01338         }
01339         return ExprError();
01340       }
01341     }
01342 
01343     if (!Type->isPointerType())
01344       return ExprError(Diag(StartLoc, diag::err_delete_operand)
01345         << Type << Ex->getSourceRange());
01346 
01347     QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
01348     if (Pointee->isFunctionType() || Pointee->isVoidType())
01349       return ExprError(Diag(StartLoc, diag::err_delete_operand)
01350         << Type << Ex->getSourceRange());
01351     else if (!Pointee->isDependentType() &&
01352              RequireCompleteType(StartLoc, Pointee,
01353                                  PDiag(diag::warn_delete_incomplete)
01354                                    << Ex->getSourceRange()))
01355       return ExprError();
01356 
01357     // C++ [expr.delete]p2:
01358     //   [Note: a pointer to a const type can be the operand of a 
01359     //   delete-expression; it is not necessary to cast away the constness 
01360     //   (5.2.11) of the pointer expression before it is used as the operand 
01361     //   of the delete-expression. ]
01362     ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), 
01363                       CastExpr::CK_NoOp);
01364     
01365     // Update the operand.
01366     Operand.take();
01367     Operand = ExprArg(*this, Ex);
01368     
01369     DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
01370                                       ArrayForm ? OO_Array_Delete : OO_Delete);
01371 
01372     if (const RecordType *RT = Pointee->getAs<RecordType>()) {
01373       CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
01374 
01375       if (!UseGlobal && 
01376           FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
01377         return ExprError();
01378       
01379       if (!RD->hasTrivialDestructor())
01380         if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
01381           MarkDeclarationReferenced(StartLoc,
01382                                     const_cast<CXXDestructorDecl*>(Dtor));
01383     }
01384     
01385     if (!OperatorDelete) {
01386       // Look for a global declaration.
01387       DeclareGlobalNewDelete();
01388       DeclContext *TUDecl = Context.getTranslationUnitDecl();
01389       if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
01390                                  &Ex, 1, TUDecl, /*AllowMissing=*/false,
01391                                  OperatorDelete))
01392         return ExprError();
01393     }
01394 
01395     // FIXME: Check access and ambiguity of operator delete and destructor.
01396   }
01397 
01398   Operand.release();
01399   return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
01400                                            OperatorDelete, Ex, StartLoc));
01401 }
01402 
01403 /// \brief Check the use of the given variable as a C++ condition in an if,
01404 /// while, do-while, or switch statement.
01405 Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
01406   QualType T = ConditionVar->getType();
01407   
01408   // C++ [stmt.select]p2:
01409   //   The declarator shall not specify a function or an array.
01410   if (T->isFunctionType())
01411     return ExprError(Diag(ConditionVar->getLocation(), 
01412                           diag::err_invalid_use_of_function_type)
01413                        << ConditionVar->getSourceRange());
01414   else if (T->isArrayType())
01415     return ExprError(Diag(ConditionVar->getLocation(), 
01416                           diag::err_invalid_use_of_array_type)
01417                      << ConditionVar->getSourceRange());
01418 
01419   return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
01420                                    ConditionVar->getLocation(), 
01421                                 ConditionVar->getType().getNonReferenceType()));
01422 }
01423 
01424 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
01425 bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
01426   // C++ 6.4p4:
01427   // The value of a condition that is an initialized declaration in a statement
01428   // other than a switch statement is the value of the declared variable
01429   // implicitly converted to type bool. If that conversion is ill-formed, the
01430   // program is ill-formed.
01431   // The value of a condition that is an expression is the value of the
01432   // expression, implicitly converted to bool.
01433   //
01434   return PerformContextuallyConvertToBool(CondExpr);
01435 }
01436 
01437 /// Helper function to determine whether this is the (deprecated) C++
01438 /// conversion from a string literal to a pointer to non-const char or
01439 /// non-const wchar_t (for narrow and wide string literals,
01440 /// respectively).
01441 bool
01442 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
01443   // Look inside the implicit cast, if it exists.
01444   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
01445     From = Cast->getSubExpr();
01446 
01447   // A string literal (2.13.4) that is not a wide string literal can
01448   // be converted to an rvalue of type "pointer to char"; a wide
01449   // string literal can be converted to an rvalue of type "pointer
01450   // to wchar_t" (C++ 4.2p2).
01451   if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
01452     if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
01453       if (const BuiltinType *ToPointeeType
01454           = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
01455         // This conversion is considered only when there is an
01456         // explicit appropriate pointer target type (C++ 4.2p2).
01457         if (!ToPtrType->getPointeeType().hasQualifiers() &&
01458             ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
01459              (!StrLit->isWide() &&
01460               (ToPointeeType->getKind() == BuiltinType::Char_U ||
01461                ToPointeeType->getKind() == BuiltinType::Char_S))))
01462           return true;
01463       }
01464 
01465   return false;
01466 }
01467 
01468 /// PerformImplicitConversion - Perform an implicit conversion of the
01469 /// expression From to the type ToType. Returns true if there was an
01470 /// error, false otherwise. The expression From is replaced with the
01471 /// converted expression. Flavor is the kind of conversion we're
01472 /// performing, used in the error message. If @p AllowExplicit,
01473 /// explicit user-defined conversions are permitted. @p Elidable should be true
01474 /// when called for copies which may be elided (C++ 12.8p15). C++0x overload
01475 /// resolution works differently in that case.
01476 bool
01477 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
01478                                 AssignmentAction Action, bool AllowExplicit,
01479                                 bool Elidable) {
01480   ImplicitConversionSequence ICS;
01481   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, 
01482                                    Elidable, ICS);
01483 }
01484 
01485 bool
01486 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
01487                                 AssignmentAction Action, bool AllowExplicit,
01488                                 bool Elidable,
01489                                 ImplicitConversionSequence& ICS) {
01490   ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
01491   if (Elidable && getLangOptions().CPlusPlus0x) {
01492     ICS = TryImplicitConversion(From, ToType,
01493                                 /*SuppressUserConversions=*/false,
01494                                 AllowExplicit,
01495                                 /*ForceRValue=*/true,
01496                                 /*InOverloadResolution=*/false);
01497   }
01498   if (ICS.isBad()) {
01499     ICS = TryImplicitConversion(From, ToType,
01500                                 /*SuppressUserConversions=*/false,
01501                                 AllowExplicit,
01502                                 /*ForceRValue=*/false,
01503                                 /*InOverloadResolution=*/false);
01504   }
01505   return PerformImplicitConversion(From, ToType, ICS, Action);
01506 }
01507 
01508 /// PerformImplicitConversion - Perform an implicit conversion of the
01509 /// expression From to the type ToType using the pre-computed implicit
01510 /// conversion sequence ICS. Returns true if there was an error, false
01511 /// otherwise. The expression From is replaced with the converted
01512 /// expression. Action is the kind of conversion we're performing,
01513 /// used in the error message.
01514 bool
01515 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
01516                                 const ImplicitConversionSequence &ICS,
01517                                 AssignmentAction Action, bool IgnoreBaseAccess) {
01518   switch (ICS.getKind()) {
01519   case ImplicitConversionSequence::StandardConversion:
01520     if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
01521                                   IgnoreBaseAccess))
01522       return true;
01523     break;
01524 
01525   case ImplicitConversionSequence::UserDefinedConversion: {
01526     
01527       FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
01528       CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
01529       QualType BeforeToType;
01530       if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
01531         CastKind = CastExpr::CK_UserDefinedConversion;
01532         
01533         // If the user-defined conversion is specified by a conversion function,
01534         // the initial standard conversion sequence converts the source type to
01535         // the implicit object parameter of the conversion function.
01536         BeforeToType = Context.getTagDeclType(Conv->getParent());
01537       } else if (const CXXConstructorDecl *Ctor = 
01538                   dyn_cast<CXXConstructorDecl>(FD)) {
01539         CastKind = CastExpr::CK_ConstructorConversion;
01540         // Do no conversion if dealing with ... for the first conversion.
01541         if (!ICS.UserDefined.EllipsisConversion) {
01542           // If the user-defined conversion is specified by a constructor, the 
01543           // initial standard conversion sequence converts the source type to the
01544           // type required by the argument of the constructor
01545           BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
01546         }
01547       }    
01548       else
01549         assert(0 && "Unknown conversion function kind!");
01550       // Whatch out for elipsis conversion.
01551       if (!ICS.UserDefined.EllipsisConversion) {
01552         if (PerformImplicitConversion(From, BeforeToType, 
01553                                       ICS.UserDefined.Before, AA_Converting,
01554                                       IgnoreBaseAccess))
01555           return true;
01556       }
01557     
01558       OwningExprResult CastArg 
01559         = BuildCXXCastArgument(From->getLocStart(),
01560                                ToType.getNonReferenceType(),
01561                                CastKind, cast<CXXMethodDecl>(FD), 
01562                                Owned(From));
01563 
01564       if (CastArg.isInvalid())
01565         return true;
01566 
01567       From = CastArg.takeAs<Expr>();
01568 
01569       return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
01570                                        AA_Converting, IgnoreBaseAccess);
01571   }
01572 
01573   case ImplicitConversionSequence::AmbiguousConversion:
01574     DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
01575                           PDiag(diag::err_typecheck_ambiguous_condition)
01576                             << From->getSourceRange());
01577      return true;
01578       
01579   case ImplicitConversionSequence::EllipsisConversion:
01580     assert(false && "Cannot perform an ellipsis conversion");
01581     return false;
01582 
01583   case ImplicitConversionSequence::BadConversion:
01584     return true;
01585   }
01586 
01587   // Everything went well.
01588   return false;
01589 }
01590 
01591 /// PerformImplicitConversion - Perform an implicit conversion of the
01592 /// expression From to the type ToType by following the standard
01593 /// conversion sequence SCS. Returns true if there was an error, false
01594 /// otherwise. The expression From is replaced with the converted
01595 /// expression. Flavor is the context in which we're performing this
01596 /// conversion, for use in error messages.
01597 bool
01598 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
01599                                 const StandardConversionSequence& SCS,
01600                                 AssignmentAction Action, bool IgnoreBaseAccess) {
01601   // Overall FIXME: we are recomputing too many types here and doing far too
01602   // much extra work. What this means is that we need to keep track of more
01603   // information that is computed when we try the implicit conversion initially,
01604   // so that we don't need to recompute anything here.
01605   QualType FromType = From->getType();
01606 
01607   if (SCS.CopyConstructor) {
01608     // FIXME: When can ToType be a reference type?
01609     assert(!ToType->isReferenceType());
01610     if (SCS.Second == ICK_Derived_To_Base) {
01611       ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
01612       if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
01613                                   MultiExprArg(*this, (void **)&From, 1),
01614                                   /*FIXME:ConstructLoc*/SourceLocation(), 
01615                                   ConstructorArgs))
01616         return true;
01617       OwningExprResult FromResult =
01618         BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
01619                               ToType, SCS.CopyConstructor,
01620                               move_arg(ConstructorArgs));
01621       if (FromResult.isInvalid())
01622         return true;
01623       From = FromResult.takeAs<Expr>();
01624       return false;
01625     }
01626     OwningExprResult FromResult =
01627       BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
01628                             ToType, SCS.CopyConstructor,
01629                             MultiExprArg(*this, (void**)&From, 1));
01630 
01631     if (FromResult.isInvalid())
01632       return true;
01633 
01634     From = FromResult.takeAs<Expr>();
01635     return false;
01636   }
01637 
01638   // Perform the first implicit conversion.
01639   switch (SCS.First) {
01640   case ICK_Identity:
01641   case ICK_Lvalue_To_Rvalue:
01642     // Nothing to do.
01643     break;
01644 
01645   case ICK_Array_To_Pointer:
01646     FromType = Context.getArrayDecayedType(FromType);
01647     ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
01648     break;
01649 
01650   case ICK_Function_To_Pointer:
01651     if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
01652       FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
01653       if (!Fn)
01654         return true;
01655 
01656       if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
01657         return true;
01658 
01659       From = FixOverloadedFunctionReference(From, Fn);
01660       FromType = From->getType();
01661         
01662       // If there's already an address-of operator in the expression, we have
01663       // the right type already, and the code below would just introduce an
01664       // invalid additional pointer level.
01665       if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
01666         break;
01667     }
01668     FromType = Context.getPointerType(FromType);
01669     ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
01670     break;
01671 
01672   default:
01673     assert(false && "Improper first standard conversion");
01674     break;
01675   }
01676 
01677   // Perform the second implicit conversion
01678   switch (SCS.Second) {
01679   case ICK_Identity:
01680     // If both sides are functions (or pointers/references to them), there could
01681     // be incompatible exception declarations.
01682     if (CheckExceptionSpecCompatibility(From, ToType))
01683       return true;
01684     // Nothing else to do.
01685     break;
01686 
01687   case ICK_NoReturn_Adjustment:
01688     // If both sides are functions (or pointers/references to them), there could
01689     // be incompatible exception declarations.
01690     if (CheckExceptionSpecCompatibility(From, ToType))
01691       return true;      
01692       
01693     ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
01694                       CastExpr::CK_NoOp);
01695     break;
01696       
01697   case ICK_Integral_Promotion:
01698   case ICK_Integral_Conversion:
01699     ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
01700     break;
01701 
01702   case ICK_Floating_Promotion:
01703   case ICK_Floating_Conversion:
01704     ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
01705     break;
01706 
01707   case ICK_Complex_Promotion:
01708   case ICK_Complex_Conversion:
01709     ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
01710     break;
01711 
01712   case ICK_Floating_Integral:
01713     if (ToType->isFloatingType())
01714       ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
01715     else
01716       ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
01717     break;
01718 
01719   case ICK_Complex_Real:
01720     ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
01721     break;
01722 
01723   case ICK_Compatible_Conversion:
01724     ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
01725     break;
01726 
01727   case ICK_Pointer_Conversion: {
01728     if (SCS.IncompatibleObjC) {
01729       // Diagnose incompatible Objective-C conversions
01730       Diag(From->getSourceRange().getBegin(),
01731            diag::ext_typecheck_convert_incompatible_pointer)
01732         << From->getType() << ToType << Action
01733         << From->getSourceRange();
01734     }
01735 
01736     
01737     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
01738     if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
01739       return true;
01740     ImpCastExprToType(From, ToType, Kind);
01741     break;
01742   }
01743   
01744   case ICK_Pointer_Member: {
01745     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
01746     if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
01747       return true;
01748     if (CheckExceptionSpecCompatibility(From, ToType))
01749       return true;
01750     ImpCastExprToType(From, ToType, Kind);
01751     break;
01752   }
01753   case ICK_Boolean_Conversion: {
01754     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
01755     if (FromType->isMemberPointerType())
01756       Kind = CastExpr::CK_MemberPointerToBoolean;
01757     
01758     ImpCastExprToType(From, Context.BoolTy, Kind);
01759     break;
01760   }
01761 
01762   case ICK_Derived_To_Base:
01763     if (CheckDerivedToBaseConversion(From->getType(), 
01764                                      ToType.getNonReferenceType(),
01765                                      From->getLocStart(),
01766                                      From->getSourceRange(),
01767                                      IgnoreBaseAccess))
01768       return true;
01769     ImpCastExprToType(From, ToType.getNonReferenceType(), 
01770                       CastExpr::CK_DerivedToBase);
01771     break;
01772       
01773   default:
01774     assert(false && "Improper second standard conversion");
01775     break;
01776   }
01777 
01778   switch (SCS.Third) {
01779   case ICK_Identity:
01780     // Nothing to do.
01781     break;
01782 
01783   case ICK_Qualification:
01784     // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
01785     // references.
01786     ImpCastExprToType(From, ToType.getNonReferenceType(),
01787                       CastExpr::CK_NoOp,
01788                       ToType->isLValueReferenceType());
01789 
01790     if (SCS.DeprecatedStringLiteralToCharPtr)
01791       Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
01792         << ToType.getNonReferenceType();
01793 
01794     break;
01795       
01796   default:
01797     assert(false && "Improper second standard conversion");
01798     break;
01799   }
01800 
01801   return false;
01802 }
01803 
01804 Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
01805                                                  SourceLocation KWLoc,
01806                                                  SourceLocation LParen,
01807                                                  TypeTy *Ty,
01808                                                  SourceLocation RParen) {
01809   QualType T = GetTypeFromParser(Ty);
01810 
01811   // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
01812   // all traits except __is_class, __is_enum and __is_union require a the type
01813   // to be complete.
01814   if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
01815     if (RequireCompleteType(KWLoc, T,
01816                             diag::err_incomplete_type_used_in_type_trait_expr))
01817       return ExprError();
01818   }
01819 
01820   // There is no point in eagerly computing the value. The traits are designed
01821   // to be used from type trait templates, so Ty will be a template parameter
01822   // 99% of the time.
01823   return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
01824                                                 RParen, Context.BoolTy));
01825 }
01826 
01827 QualType Sema::CheckPointerToMemberOperands(
01828   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
01829   const char *OpSpelling = isIndirect ? "->*" : ".*";
01830   // C++ 5.5p2
01831   //   The binary operator .* [p3: ->*] binds its second operand, which shall
01832   //   be of type "pointer to member of T" (where T is a completely-defined
01833   //   class type) [...]
01834   QualType RType = rex->getType();
01835   const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
01836   if (!MemPtr) {
01837     Diag(Loc, diag::err_bad_memptr_rhs)
01838       << OpSpelling << RType << rex->getSourceRange();
01839     return QualType();
01840   }
01841 
01842   QualType Class(MemPtr->getClass(), 0);
01843 
01844   // C++ 5.5p2
01845   //   [...] to its first operand, which shall be of class T or of a class of
01846   //   which T is an unambiguous and accessible base class. [p3: a pointer to
01847   //   such a class]
01848   QualType LType = lex->getType();
01849   if (isIndirect) {
01850     if (const PointerType *Ptr = LType->getAs<PointerType>())
01851       LType = Ptr->getPointeeType().getNonReferenceType();
01852     else {
01853       Diag(Loc, diag::err_bad_memptr_lhs)
01854         << OpSpelling << 1 << LType
01855         << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
01856       return QualType();
01857     }
01858   }
01859 
01860   if (!Context.hasSameUnqualifiedType(Class, LType)) {
01861     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
01862                        /*DetectVirtual=*/false);
01863     // FIXME: Would it be useful to print full ambiguity paths, or is that
01864     // overkill?
01865     if (!IsDerivedFrom(LType, Class, Paths) ||
01866         Paths.isAmbiguous(Context.getCanonicalType(Class))) {
01867       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
01868         << (int)isIndirect << lex->getType();
01869       return QualType();
01870     }
01871     // Cast LHS to type of use.
01872     QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
01873     bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
01874     ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
01875   }
01876 
01877   if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
01878     // Diagnose use of pointer-to-member type which when used as
01879     // the functional cast in a pointer-to-member expression.
01880     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
01881      return QualType();
01882   }
01883   // C++ 5.5p2
01884   //   The result is an object or a function of the type specified by the
01885   //   second operand.
01886   // The cv qualifiers are the union of those in the pointer and the left side,
01887   // in accordance with 5.5p5 and 5.2.5.
01888   // FIXME: This returns a dereferenced member function pointer as a normal
01889   // function type. However, the only operation valid on such functions is
01890   // calling them. There's also a GCC extension to get a function pointer to the
01891   // thing, which is another complication, because this type - unlike the type
01892   // that is the result of this expression - takes the class as the first
01893   // argument.
01894   // We probably need a "MemberFunctionClosureType" or something like that.
01895   QualType Result = MemPtr->getPointeeType();
01896   Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
01897   return Result;
01898 }
01899 
01900 /// \brief Get the target type of a standard or user-defined conversion.
01901 static QualType TargetType(const ImplicitConversionSequence &ICS) {
01902   switch (ICS.getKind()) {
01903   case ImplicitConversionSequence::StandardConversion:
01904     return ICS.Standard.getToType(2);
01905   case ImplicitConversionSequence::UserDefinedConversion:
01906     return ICS.UserDefined.After.getToType(2);
01907   case ImplicitConversionSequence::AmbiguousConversion:
01908     return ICS.Ambiguous.getToType();
01909 
01910   case ImplicitConversionSequence::EllipsisConversion:
01911   case ImplicitConversionSequence::BadConversion:
01912     llvm_unreachable("function not valid for ellipsis or bad conversions");
01913   }
01914   return QualType(); // silence warnings
01915 }
01916 
01917 /// \brief Try to convert a type to another according to C++0x 5.16p3.
01918 ///
01919 /// This is part of the parameter validation for the ? operator. If either
01920 /// value operand is a class type, the two operands are attempted to be
01921 /// converted to each other. This function does the conversion in one direction.
01922 /// It emits a diagnostic and returns true only if it finds an ambiguous
01923 /// conversion.
01924 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
01925                                 SourceLocation QuestionLoc,
01926                                 ImplicitConversionSequence &ICS) {
01927   // C++0x 5.16p3
01928   //   The process for determining whether an operand expression E1 of type T1
01929   //   can be converted to match an operand expression E2 of type T2 is defined
01930   //   as follows:
01931   //   -- If E2 is an lvalue:
01932   if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
01933     //   E1 can be converted to match E2 if E1 can be implicitly converted to
01934     //   type "lvalue reference to T2", subject to the constraint that in the
01935     //   conversion the reference must bind directly to E1.
01936     if (!Self.CheckReferenceInit(From,
01937                             Self.Context.getLValueReferenceType(To->getType()),
01938                                  To->getLocStart(),
01939                                  /*SuppressUserConversions=*/false,
01940                                  /*AllowExplicit=*/false,
01941                                  /*ForceRValue=*/false,
01942                                  &ICS))
01943     {
01944       assert((ICS.isStandard() || ICS.isUserDefined()) &&
01945              "expected a definite conversion");
01946       bool DirectBinding =
01947         ICS.isStandard() ? ICS.Standard.DirectBinding
01948                          : ICS.UserDefined.After.DirectBinding;
01949       if (DirectBinding)
01950         return false;
01951     }
01952   }
01953 
01954   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
01955   //      -- if E1 and E2 have class type, and the underlying class types are
01956   //         the same or one is a base class of the other:
01957   QualType FTy = From->getType();
01958   QualType TTy = To->getType();
01959   const RecordType *FRec = FTy->getAs<RecordType>();
01960   const RecordType *TRec = TTy->getAs<RecordType>();
01961   bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
01962   if (FRec && TRec && (FRec == TRec ||
01963         FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
01964     //         E1 can be converted to match E2 if the class of T2 is the
01965     //         same type as, or a base class of, the class of T1, and
01966     //         [cv2 > cv1].
01967     if (FRec == TRec || FDerivedFromT) {
01968       if (TTy.isAtLeastAsQualifiedAs(FTy)) {
01969         // Could still fail if there's no copy constructor.
01970         // FIXME: Is this a hard error then, or just a conversion failure? The
01971         // standard doesn't say.
01972         ICS = Self.TryCopyInitialization(From, TTy,
01973                                          /*SuppressUserConversions=*/false,
01974                                          /*ForceRValue=*/false,
01975                                          /*InOverloadResolution=*/false);
01976       } else {
01977         ICS.setBad(BadConversionSequence::bad_qualifiers, From, TTy);
01978       }
01979     } else {
01980       // Can't implicitly convert FTy to a derived class TTy.
01981       // TODO: more specific error for this.
01982       ICS.setBad(BadConversionSequence::no_conversion, From, TTy);
01983     }
01984   } else {
01985     //     -- Otherwise: E1 can be converted to match E2 if E1 can be
01986     //        implicitly converted to the type that expression E2 would have
01987     //        if E2 were converted to an rvalue.
01988     // First find the decayed type.
01989     if (TTy->isFunctionType())
01990       TTy = Self.Context.getPointerType(TTy);
01991     else if (TTy->isArrayType())
01992       TTy = Self.Context.getArrayDecayedType(TTy);
01993 
01994     // Now try the implicit conversion.
01995     // FIXME: This doesn't detect ambiguities.
01996     ICS = Self.TryImplicitConversion(From, TTy,
01997                                      /*SuppressUserConversions=*/false,
01998                                      /*AllowExplicit=*/false,
01999                                      /*ForceRValue=*/false,
02000                                      /*InOverloadResolution=*/false);
02001   }
02002   return false;
02003 }
02004 
02005 /// \brief Try to find a common type for two according to C++0x 5.16p5.
02006 ///
02007 /// This is part of the parameter validation for the ? operator. If either
02008 /// value operand is a class type, overload resolution is used to find a
02009 /// conversion to a common type.
02010 static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
02011                                     SourceLocation Loc) {
02012   Expr *Args[2] = { LHS, RHS };
02013   OverloadCandidateSet CandidateSet(Loc);
02014   Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
02015 
02016   OverloadCandidateSet::iterator Best;
02017   switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
02018     case OR_Success:
02019       // We found a match. Perform the conversions on the arguments and move on.
02020       if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
02021                                          Best->Conversions[0], Sema::AA_Converting) ||
02022           Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
02023                                          Best->Conversions[1], Sema::AA_Converting))
02024         break;
02025       return false;
02026 
02027     case OR_No_Viable_Function:
02028       Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
02029         << LHS->getType() << RHS->getType()
02030         << LHS->getSourceRange() << RHS->getSourceRange();
02031       return true;
02032 
02033     case OR_Ambiguous:
02034       Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
02035         << LHS->getType() << RHS->getType()
02036         << LHS->getSourceRange() << RHS->getSourceRange();
02037       // FIXME: Print the possible common types by printing the return types of
02038       // the viable candidates.
02039       break;
02040 
02041     case OR_Deleted:
02042       assert(false && "Conditional operator has only built-in overloads");
02043       break;
02044   }
02045   return true;
02046 }
02047 
02048 /// \brief Perform an "extended" implicit conversion as returned by
02049 /// TryClassUnification.
02050 ///
02051 /// TryClassUnification generates ICSs that include reference bindings.
02052 /// PerformImplicitConversion is not suitable for this; it chokes if the
02053 /// second part of a standard conversion is ICK_DerivedToBase. This function
02054 /// handles the reference binding specially.
02055 static bool ConvertForConditional(Sema &Self, Expr *&E,
02056                                   const ImplicitConversionSequence &ICS) {
02057   if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
02058     assert(ICS.Standard.DirectBinding &&
02059            "TryClassUnification should never generate indirect ref bindings");
02060     // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
02061     // redoing all the work.
02062     return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
02063                                         TargetType(ICS)),
02064                                    /*FIXME:*/E->getLocStart(),
02065                                    /*SuppressUserConversions=*/false,
02066                                    /*AllowExplicit=*/false,
02067                                    /*ForceRValue=*/false);
02068   }
02069   if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
02070     assert(ICS.UserDefined.After.DirectBinding &&
02071            "TryClassUnification should never generate indirect ref bindings");
02072     return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
02073                                         TargetType(ICS)),
02074                                    /*FIXME:*/E->getLocStart(),
02075                                    /*SuppressUserConversions=*/false,
02076                                    /*AllowExplicit=*/false,
02077                                    /*ForceRValue=*/false);
02078   }
02079   if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
02080     return true;
02081   return false;
02082 }
02083 
02084 /// \brief Check the operands of ?: under C++ semantics.
02085 ///
02086 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
02087 /// extension. In this case, LHS == Cond. (But they're not aliases.)
02088 QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
02089                                            SourceLocation QuestionLoc) {
02090   // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
02091   // interface pointers.
02092 
02093   // C++0x 5.16p1
02094   //   The first expression is contextually converted to bool.
02095   if (!Cond->isTypeDependent()) {
02096     if (CheckCXXBooleanCondition(Cond))
02097       return QualType();
02098   }
02099 
02100   // Either of the arguments dependent?
02101   if (LHS->isTypeDependent() || RHS->isTypeDependent())
02102     return Context.DependentTy;
02103 
02104   CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
02105 
02106   // C++0x 5.16p2
02107   //   If either the second or the third operand has type (cv) void, ...
02108   QualType LTy = LHS->getType();
02109   QualType RTy = RHS->getType();
02110   bool LVoid = LTy->isVoidType();
02111   bool RVoid = RTy->isVoidType();
02112   if (LVoid || RVoid) {
02113     //   ... then the [l2r] conversions are performed on the second and third
02114     //   operands ...
02115     DefaultFunctionArrayLvalueConversion(LHS);
02116     DefaultFunctionArrayLvalueConversion(RHS);
02117     LTy = LHS->getType();
02118     RTy = RHS->getType();
02119 
02120     //   ... and one of the following shall hold:
02121     //   -- The second or the third operand (but not both) is a throw-
02122     //      expression; the result is of the type of the other and is an rvalue.
02123     bool LThrow = isa<CXXThrowExpr>(LHS);
02124     bool RThrow = isa<CXXThrowExpr>(RHS);
02125     if (LThrow && !RThrow)
02126       return RTy;
02127     if (RThrow && !LThrow)
02128       return LTy;
02129 
02130     //   -- Both the second and third operands have type void; the result is of
02131     //      type void and is an rvalue.
02132     if (LVoid && RVoid)
02133       return Context.VoidTy;
02134 
02135     // Neither holds, error.
02136     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
02137       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
02138       << LHS->getSourceRange() << RHS->getSourceRange();
02139     return QualType();
02140   }
02141 
02142   // Neither is void.
02143 
02144   // C++0x 5.16p3
02145   //   Otherwise, if the second and third operand have different types, and
02146   //   either has (cv) class type, and attempt is made to convert each of those
02147   //   operands to the other.
02148   if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
02149       (LTy->isRecordType() || RTy->isRecordType())) {
02150     ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
02151     // These return true if a single direction is already ambiguous.
02152     if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
02153       return QualType();
02154     if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
02155       return QualType();
02156 
02157     bool HaveL2R = !ICSLeftToRight.isBad();
02158     bool HaveR2L = !ICSRightToLeft.isBad();
02159     //   If both can be converted, [...] the program is ill-formed.
02160     if (HaveL2R && HaveR2L) {
02161       Diag(QuestionLoc, diag::err_conditional_ambiguous)
02162         << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
02163       return QualType();
02164     }
02165 
02166     //   If exactly one conversion is possible, that conversion is applied to
02167     //   the chosen operand and the converted operands are used in place of the
02168     //   original operands for the remainder of this section.
02169     if (HaveL2R) {
02170       if (ConvertForConditional(*this, LHS, ICSLeftToRight))
02171         return QualType();
02172       LTy = LHS->getType();
02173     } else if (HaveR2L) {
02174       if (ConvertForConditional(*this, RHS, ICSRightToLeft))
02175         return QualType();
02176       RTy = RHS->getType();
02177     }
02178   }
02179 
02180   // C++0x 5.16p4
02181   //   If the second and third operands are lvalues and have the same type,
02182   //   the result is of that type [...]
02183   bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
02184   if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
02185       RHS->isLvalue(Context) == Expr::LV_Valid)
02186     return LTy;
02187 
02188   // C++0x 5.16p5
02189   //   Otherwise, the result is an rvalue. If the second and third operands
02190   //   do not have the same type, and either has (cv) class type, ...
02191   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
02192     //   ... overload resolution is used to determine the conversions (if any)
02193     //   to be applied to the operands. If the overload resolution fails, the
02194     //   program is ill-formed.
02195     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
02196       return QualType();
02197   }
02198 
02199   // C++0x 5.16p6
02200   //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
02201   //   conversions are performed on the second and third operands.
02202   DefaultFunctionArrayLvalueConversion(LHS);
02203   DefaultFunctionArrayLvalueConversion(RHS);
02204   LTy = LHS->getType();
02205   RTy = RHS->getType();
02206 
02207   //   After those conversions, one of the following shall hold:
02208   //   -- The second and third operands have the same type; the result
02209   //      is of that type.
02210   if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
02211     return LTy;
02212 
02213   //   -- The second and third operands have arithmetic or enumeration type;
02214   //      the usual arithmetic conversions are performed to bring them to a
02215   //      common type, and the result is of that type.
02216   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
02217     UsualArithmeticConversions(LHS, RHS);
02218     return LHS->getType();
02219   }
02220 
02221   //   -- The second and third operands have pointer type, or one has pointer
02222   //      type and the other is a null pointer constant; pointer conversions
02223   //      and qualification conversions are performed to bring them to their
02224   //      composite pointer type. The result is of the composite pointer type.
02225   //   -- The second and third operands have pointer to member type, or one has
02226   //      pointer to member type and the other is a null pointer constant;
02227   //      pointer to member conversions and qualification conversions are
02228   //      performed to bring them to a common type, whose cv-qualification
02229   //      shall match the cv-qualification of either the second or the third
02230   //      operand. The result is of the common type.
02231   bool NonStandardCompositeType = false;
02232   QualType Composite = FindCompositePointerType(LHS, RHS,
02233                               isSFINAEContext()? 0 : &NonStandardCompositeType);
02234   if (!Composite.isNull()) {
02235     if (NonStandardCompositeType)
02236       Diag(QuestionLoc, 
02237            diag::ext_typecheck_cond_incompatible_operands_nonstandard)
02238         << LTy << RTy << Composite
02239         << LHS->getSourceRange() << RHS->getSourceRange();
02240       
02241     return Composite;
02242   }
02243   
02244   // Similarly, attempt to find composite type of twp objective-c pointers.
02245   Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
02246   if (!Composite.isNull())
02247     return Composite;
02248 
02249   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
02250     << LHS->getType() << RHS->getType()
02251     << LHS->getSourceRange() << RHS->getSourceRange();
02252   return QualType();
02253 }
02254 
02255 /// \brief Find a merged pointer type and convert the two expressions to it.
02256 ///
02257 /// This finds the composite pointer type (or member pointer type) for @p E1
02258 /// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
02259 /// type and returns it.
02260 /// It does not emit diagnostics.
02261 ///
02262 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
02263 /// a non-standard (but still sane) composite type to which both expressions
02264 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
02265 /// will be set true.
02266 QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2,
02267                                         bool *NonStandardCompositeType) {
02268   if (NonStandardCompositeType)
02269     *NonStandardCompositeType = false;
02270   
02271   assert(getLangOptions().CPlusPlus && "This function assumes C++");
02272   QualType T1 = E1->getType(), T2 = E2->getType();
02273 
02274   if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
02275       !T2->isAnyPointerType() && !T2->isMemberPointerType())
02276    return QualType();
02277 
02278   // C++0x 5.9p2
02279   //   Pointer conversions and qualification conversions are performed on
02280   //   pointer operands to bring them to their composite pointer type. If
02281   //   one operand is a null pointer constant, the composite pointer type is
02282   //   the type of the other operand.
02283   if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
02284     if (T2->isMemberPointerType())
02285       ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
02286     else
02287       ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
02288     return T2;
02289   }
02290   if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
02291     if (T1->isMemberPointerType())
02292       ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
02293     else
02294       ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
02295     return T1;
02296   }
02297 
02298   // Now both have to be pointers or member pointers.
02299   if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
02300       (!T2->isPointerType() && !T2->isMemberPointerType()))
02301     return QualType();
02302 
02303   //   Otherwise, of one of the operands has type "pointer to cv1 void," then
02304   //   the other has type "pointer to cv2 T" and the composite pointer type is
02305   //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
02306   //   Otherwise, the composite pointer type is a pointer type similar to the
02307   //   type of one of the operands, with a cv-qualification signature that is
02308   //   the union of the cv-qualification signatures of the operand types.
02309   // In practice, the first part here is redundant; it's subsumed by the second.
02310   // What we do here is, we build the two possible composite types, and try the
02311   // conversions in both directions. If only one works, or if the two composite
02312   // types are the same, we have succeeded.
02313   // FIXME: extended qualifiers?
02314   typedef llvm::SmallVector<unsigned, 4> QualifierVector;
02315   QualifierVector QualifierUnion;
02316   typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
02317       ContainingClassVector;
02318   ContainingClassVector MemberOfClass;
02319   QualType Composite1 = Context.getCanonicalType(T1),
02320            Composite2 = Context.getCanonicalType(T2);
02321   unsigned NeedConstBefore = 0;  
02322   do {
02323     const PointerType *Ptr1, *Ptr2;
02324     if ((Ptr1 = Composite1->getAs<PointerType>()) &&
02325         (Ptr2 = Composite2->getAs<PointerType>())) {
02326       Composite1 = Ptr1->getPointeeType();
02327       Composite2 = Ptr2->getPointeeType();
02328       
02329       // If we're allowed to create a non-standard composite type, keep track
02330       // of where we need to fill in additional 'const' qualifiers. 
02331       if (NonStandardCompositeType &&
02332           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
02333         NeedConstBefore = QualifierUnion.size();
02334       
02335       QualifierUnion.push_back(
02336                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
02337       MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
02338       continue;
02339     }
02340 
02341     const MemberPointerType *MemPtr1, *MemPtr2;
02342     if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
02343         (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
02344       Composite1 = MemPtr1->getPointeeType();
02345       Composite2 = MemPtr2->getPointeeType();
02346       
02347       // If we're allowed to create a non-standard composite type, keep track
02348       // of where we need to fill in additional 'const' qualifiers. 
02349       if (NonStandardCompositeType &&
02350           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
02351         NeedConstBefore = QualifierUnion.size();
02352       
02353       QualifierUnion.push_back(
02354                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
02355       MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
02356                                              MemPtr2->getClass()));
02357       continue;
02358     }
02359 
02360     // FIXME: block pointer types?
02361 
02362     // Cannot unwrap any more types.
02363     break;
02364   } while (true);
02365 
02366   if (NeedConstBefore && NonStandardCompositeType) {
02367     // Extension: Add 'const' to qualifiers that come before the first qualifier
02368     // mismatch, so that our (non-standard!) composite type meets the 
02369     // requirements of C++ [conv.qual]p4 bullet 3.
02370     for (unsigned I = 0; I != NeedConstBefore; ++I) {
02371       if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
02372         QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
02373         *NonStandardCompositeType = true;
02374       }
02375     }
02376   }
02377   
02378   // Rewrap the composites as pointers or member pointers with the union CVRs.
02379   ContainingClassVector::reverse_iterator MOC
02380     = MemberOfClass.rbegin();
02381   for (QualifierVector::reverse_iterator
02382          I = QualifierUnion.rbegin(),
02383          E = QualifierUnion.rend();
02384        I != E; (void)++I, ++MOC) {
02385     Qualifiers Quals = Qualifiers::fromCVRMask(*I);
02386     if (MOC->first && MOC->second) {
02387       // Rebuild member pointer type
02388       Composite1 = Context.getMemberPointerType(
02389                                     Context.getQualifiedType(Composite1, Quals),
02390                                     MOC->first);
02391       Composite2 = Context.getMemberPointerType(
02392                                     Context.getQualifiedType(Composite2, Quals),
02393                                     MOC->second);
02394     } else {
02395       // Rebuild pointer type
02396       Composite1
02397         = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
02398       Composite2
02399         = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
02400     }
02401   }
02402 
02403   ImplicitConversionSequence E1ToC1 =
02404     TryImplicitConversion(E1, Composite1,
02405                           /*SuppressUserConversions=*/false,
02406                           /*AllowExplicit=*/false,
02407                           /*ForceRValue=*/false,
02408                           /*InOverloadResolution=*/false);
02409   ImplicitConversionSequence E2ToC1 =
02410     TryImplicitConversion(E2, Composite1,
02411                           /*SuppressUserConversions=*/false,
02412                           /*AllowExplicit=*/false,
02413                           /*ForceRValue=*/false,
02414                           /*InOverloadResolution=*/false);
02415 
02416   bool ToC2Viable = false;
02417   ImplicitConversionSequence E1ToC2, E2ToC2;
02418   if (Context.getCanonicalType(Composite1) !=
02419       Context.getCanonicalType(Composite2)) {
02420     E1ToC2 = TryImplicitConversion(E1, Composite2,
02421                                    /*SuppressUserConversions=*/false,
02422                                    /*AllowExplicit=*/false,
02423                                    /*ForceRValue=*/false,
02424                                    /*InOverloadResolution=*/false);
02425     E2ToC2 = TryImplicitConversion(E2, Composite2,
02426                                    /*SuppressUserConversions=*/false,
02427                                    /*AllowExplicit=*/false,
02428                                    /*ForceRValue=*/false,
02429                                    /*InOverloadResolution=*/false);
02430     ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
02431   }
02432 
02433   bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
02434   if (ToC1Viable && !ToC2Viable) {
02435     if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
02436         !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
02437       return Composite1;
02438   }
02439   if (ToC2Viable && !ToC1Viable) {
02440     if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
02441         !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
02442       return Composite2;
02443   }
02444   return QualType();
02445 }
02446 
02447 Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
02448   if (!Context.getLangOptions().CPlusPlus)
02449     return Owned(E);
02450 
02451   assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
02452 
02453   const RecordType *RT = E->getType()->getAs<RecordType>();
02454   if (!RT)
02455     return Owned(E);
02456 
02457   // If this is the result of a call expression, our source might
02458   // actually be a reference, in which case we shouldn't bind.
02459   if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
02460     QualType Ty = CE->getCallee()->getType();
02461     if (const PointerType *PT = Ty->getAs<PointerType>())
02462       Ty = PT->getPointeeType();
02463     else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
02464       Ty = BPT->getPointeeType();
02465 
02466     const FunctionType *FTy = Ty->getAs<FunctionType>();
02467     if (FTy->getResultType()->isReferenceType())
02468       return Owned(E);
02469   }
02470 
02471   // That should be enough to guarantee that this type is complete.
02472   // If it has a trivial destructor, we can avoid the extra copy.
02473   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
02474   if (RD->hasTrivialDestructor())
02475     return Owned(E);
02476 
02477   CXXTemporary *Temp = CXXTemporary::Create(Context,
02478                                             RD->getDestructor(Context));
02479   ExprTemporaries.push_back(Temp);
02480   if (CXXDestructorDecl *Destructor =
02481         const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
02482     MarkDeclarationReferenced(E->getExprLoc(), Destructor);
02483   // FIXME: Add the temporary to the temporaries vector.
02484   return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
02485 }
02486 
02487 Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
02488   assert(SubExpr && "sub expression can't be null!");
02489 
02490   unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
02491   assert(ExprTemporaries.size() >= FirstTemporary);
02492   if (ExprTemporaries.size() == FirstTemporary)
02493     return SubExpr;
02494 
02495   Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
02496                                            &ExprTemporaries[FirstTemporary],
02497                                        ExprTemporaries.size() - FirstTemporary);
02498   ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
02499                         ExprTemporaries.end());
02500 
02501   return E;
02502 }
02503 
02504 Sema::OwningExprResult 
02505 Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
02506   if (SubExpr.isInvalid())
02507     return ExprError();
02508   
02509   return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
02510 }
02511 
02512 FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
02513   unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
02514   assert(ExprTemporaries.size() >= FirstTemporary);
02515   
02516   unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
02517   CXXTemporary **Temporaries = 
02518     NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
02519   
02520   FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
02521 
02522   ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
02523                         ExprTemporaries.end());
02524 
02525   return E;
02526 }
02527 
02528 Sema::OwningExprResult
02529 Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
02530                                    tok::TokenKind OpKind, TypeTy *&ObjectType,
02531                                    bool &MayBePseudoDestructor) {
02532   // Since this might be a postfix expression, get rid of ParenListExprs.
02533   Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
02534 
02535   Expr *BaseExpr = (Expr*)Base.get();
02536   assert(BaseExpr && "no record expansion");
02537 
02538   QualType BaseType = BaseExpr->getType();
02539   MayBePseudoDestructor = false;
02540   if (BaseType->isDependentType()) {
02541     // If we have a pointer to a dependent type and are using the -> operator,
02542     // the object type is the type that the pointer points to. We might still
02543     // have enough information about that type to do something useful.
02544     if (OpKind == tok::arrow)
02545       if (const PointerType *Ptr = BaseType->getAs<PointerType>())
02546         BaseType = Ptr->getPointeeType();
02547     
02548     ObjectType = BaseType.getAsOpaquePtr();
02549     MayBePseudoDestructor = true;
02550     return move(Base);
02551   }
02552 
02553   // C++ [over.match.oper]p8:
02554   //   [...] When operator->returns, the operator-> is applied  to the value
02555   //   returned, with the original second operand.
02556   if (OpKind == tok::arrow) {
02557     // The set of types we've considered so far.
02558     llvm::SmallPtrSet<CanQualType,8> CTypes;
02559     llvm::SmallVector<SourceLocation, 8> Locations;
02560     CTypes.insert(Context.getCanonicalType(BaseType));
02561     
02562     while (BaseType->isRecordType()) {
02563       Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
02564       BaseExpr = (Expr*)Base.get();
02565       if (BaseExpr == NULL)
02566         return ExprError();
02567       if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
02568         Locations.push_back(OpCall->getDirectCallee()->getLocation());
02569       BaseType = BaseExpr->getType();
02570       CanQualType CBaseType = Context.getCanonicalType(BaseType);
02571       if (!CTypes.insert(CBaseType)) {
02572         Diag(OpLoc, diag::err_operator_arrow_circular);
02573         for (unsigned i = 0; i < Locations.size(); i++)
02574           Diag(Locations[i], diag::note_declared_at);
02575         return ExprError();
02576       }
02577     }
02578 
02579     if (BaseType->isPointerType())
02580       BaseType = BaseType->getPointeeType();
02581   }
02582 
02583   // We could end up with various non-record types here, such as extended
02584   // vector types or Objective-C interfaces. Just return early and let
02585   // ActOnMemberReferenceExpr do the work.
02586   if (!BaseType->isRecordType()) {
02587     // C++ [basic.lookup.classref]p2:
02588     //   [...] If the type of the object expression is of pointer to scalar
02589     //   type, the unqualified-id is looked up in the context of the complete
02590     //   postfix-expression.
02591     //
02592     // This also indicates that we should be parsing a
02593     // pseudo-destructor-name.
02594     ObjectType = 0;
02595     MayBePseudoDestructor = true;
02596     return move(Base);
02597   }
02598 
02599   // The object type must be complete (or dependent).
02600   if (!BaseType->isDependentType() &&
02601       RequireCompleteType(OpLoc, BaseType, 
02602                           PDiag(diag::err_incomplete_member_access)))
02603     return ExprError();
02604   
02605   // C++ [basic.lookup.classref]p2:
02606   //   If the id-expression in a class member access (5.2.5) is an
02607   //   unqualified-id, and the type of the object expression is of a class
02608   //   type C (or of pointer to a class type C), the unqualified-id is looked
02609   //   up in the scope of class C. [...]
02610   ObjectType = BaseType.getAsOpaquePtr();
02611   return move(Base);
02612 }
02613 
02614 Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
02615                                                    ExprArg MemExpr) {
02616   Expr *E = (Expr *) MemExpr.get();
02617   SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
02618   Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
02619     << isa<CXXPseudoDestructorExpr>(E)
02620     << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
02621   
02622   return ActOnCallExpr(/*Scope*/ 0,
02623                        move(MemExpr),
02624                        /*LPLoc*/ ExpectedLParenLoc,
02625                        Sema::MultiExprArg(*this, 0, 0),
02626                        /*CommaLocs*/ 0,
02627                        /*RPLoc*/ ExpectedLParenLoc);
02628 }
02629 
02630 Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
02631                                                        SourceLocation OpLoc,
02632                                                        tok::TokenKind OpKind,
02633                                                        const CXXScopeSpec &SS,
02634                                                  TypeSourceInfo *ScopeTypeInfo,
02635                                                        SourceLocation CCLoc,
02636                                                        SourceLocation TildeLoc,
02637                                          PseudoDestructorTypeStorage Destructed,
02638                                                        bool HasTrailingLParen) {
02639   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
02640   
02641   // C++ [expr.pseudo]p2:
02642   //   The left-hand side of the dot operator shall be of scalar type. The 
02643   //   left-hand side of the arrow operator shall be of pointer to scalar type.
02644   //   This scalar type is the object type. 
02645   Expr *BaseE = (Expr *)Base.get();
02646   QualType ObjectType = BaseE->getType();
02647   if (OpKind == tok::arrow) {
02648     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
02649       ObjectType = Ptr->getPointeeType();
02650     } else if (!BaseE->isTypeDependent()) {
02651       // The user wrote "p->" when she probably meant "p."; fix it.
02652       Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
02653         << ObjectType << true
02654         << CodeModificationHint::CreateReplacement(OpLoc, ".");
02655       if (isSFINAEContext())
02656         return ExprError();
02657       
02658       OpKind = tok::period;
02659     }
02660   }
02661   
02662   if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
02663     Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
02664       << ObjectType << BaseE->getSourceRange();
02665     return ExprError();
02666   }
02667 
02668   // C++ [expr.pseudo]p2:
02669   //   [...] The cv-unqualified versions of the object type and of the type 
02670   //   designated by the pseudo-destructor-name shall be the same type.
02671   if (DestructedTypeInfo) {
02672     QualType DestructedType = DestructedTypeInfo->getType();
02673     SourceLocation DestructedTypeStart
02674       = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
02675     if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
02676         !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
02677       Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
02678         << ObjectType << DestructedType << BaseE->getSourceRange()
02679         << DestructedTypeInfo->getTypeLoc().getSourceRange();
02680       
02681       // Recover by setting the destructed type to the object type.
02682       DestructedType = ObjectType;
02683       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
02684                                                            DestructedTypeStart);
02685       Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
02686     }
02687   }
02688   
02689   // C++ [expr.pseudo]p2:
02690   //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
02691   //   form
02692   //
02693   //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 
02694   //
02695   //   shall designate the same scalar type.
02696   if (ScopeTypeInfo) {
02697     QualType ScopeType = ScopeTypeInfo->getType();
02698     if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
02699         !Context.hasSameType(ScopeType, ObjectType)) {
02700       
02701       Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
02702            diag::err_pseudo_dtor_type_mismatch)
02703         << ObjectType << ScopeType << BaseE->getSourceRange()
02704         << ScopeTypeInfo->getTypeLoc().getSourceRange();
02705   
02706       ScopeType = QualType();
02707       ScopeTypeInfo = 0;
02708     }
02709   }
02710   
02711   OwningExprResult Result
02712     = Owned(new (Context) CXXPseudoDestructorExpr(Context, 
02713                                                   Base.takeAs<Expr>(),
02714                                                   OpKind == tok::arrow,
02715                                                   OpLoc,
02716                                        (NestedNameSpecifier *) SS.getScopeRep(),
02717                                                   SS.getRange(),
02718                                                   ScopeTypeInfo,
02719                                                   CCLoc,
02720                                                   TildeLoc,
02721                                                   Destructed));
02722             
02723   if (HasTrailingLParen)
02724     return move(Result);
02725   
02726   return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
02727 }
02728 
02729 Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
02730                                                        SourceLocation OpLoc,
02731                                                        tok::TokenKind OpKind,
02732                                                        const CXXScopeSpec &SS,
02733                                                   UnqualifiedId &FirstTypeName,
02734                                                        SourceLocation CCLoc,
02735                                                        SourceLocation TildeLoc,
02736                                                  UnqualifiedId &SecondTypeName,
02737                                                        bool HasTrailingLParen) {
02738   assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
02739           FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
02740          "Invalid first type name in pseudo-destructor");
02741   assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
02742           SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
02743          "Invalid second type name in pseudo-destructor");
02744 
02745   Expr *BaseE = (Expr *)Base.get();
02746   
02747   // C++ [expr.pseudo]p2:
02748   //   The left-hand side of the dot operator shall be of scalar type. The 
02749   //   left-hand side of the arrow operator shall be of pointer to scalar type.
02750   //   This scalar type is the object type. 
02751   QualType ObjectType = BaseE->getType();
02752   if (OpKind == tok::arrow) {
02753     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
02754       ObjectType = Ptr->getPointeeType();
02755     } else if (!ObjectType->isDependentType()) {
02756       // The user wrote "p->" when she probably meant "p."; fix it.
02757       Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
02758         << ObjectType << true
02759         << CodeModificationHint::CreateReplacement(OpLoc, ".");
02760       if (isSFINAEContext())
02761         return ExprError();
02762       
02763       OpKind = tok::period;
02764     }
02765   }
02766 
02767   // Compute the object type that we should use for name lookup purposes. Only
02768   // record types and dependent types matter.
02769   void *ObjectTypePtrForLookup = 0;
02770   if (!SS.isSet()) {
02771     ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
02772     if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
02773       ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
02774   }
02775   
02776   // Convert the name of the type being destructed (following the ~) into a 
02777   // type (with source-location information).
02778   QualType DestructedType;
02779   TypeSourceInfo *DestructedTypeInfo = 0;
02780   PseudoDestructorTypeStorage Destructed;
02781   if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
02782     TypeTy *T = getTypeName(*SecondTypeName.Identifier, 
02783                             SecondTypeName.StartLocation,
02784                             S, &SS, true, ObjectTypePtrForLookup);
02785     if (!T && 
02786         ((SS.isSet() && !computeDeclContext(SS, false)) ||
02787          (!SS.isSet() && ObjectType->isDependentType()))) {
02788       // The name of the type being destroyed is a dependent name, and we 
02789       // couldn't find anything useful in scope. Just store the identifier and
02790       // it's location, and we'll perform (qualified) name lookup again at
02791       // template instantiation time.
02792       Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
02793                                                SecondTypeName.StartLocation);
02794     } else if (!T) {
02795       Diag(SecondTypeName.StartLocation, 
02796            diag::err_pseudo_dtor_destructor_non_type)
02797         << SecondTypeName.Identifier << ObjectType;
02798       if (isSFINAEContext())
02799         return ExprError();
02800       
02801       // Recover by assuming we had the right type all along.
02802       DestructedType = ObjectType;
02803     } else
02804       DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
02805   } else {
02806     // Resolve the template-id to a type.
02807     TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
02808     ASTTemplateArgsPtr TemplateArgsPtr(*this,
02809                                        TemplateId->getTemplateArgs(),
02810                                        TemplateId->NumArgs);
02811     TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
02812                                        TemplateId->TemplateNameLoc,
02813                                        TemplateId->LAngleLoc,
02814                                        TemplateArgsPtr,
02815                                        TemplateId->RAngleLoc);
02816     if (T.isInvalid() || !T.get()) {
02817       // Recover by assuming we had the right type all along.
02818       DestructedType = ObjectType;
02819     } else
02820       DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
02821   }
02822   
02823   // If we've performed some kind of recovery, (re-)build the type source 
02824   // information.
02825   if (!DestructedType.isNull()) {
02826     if (!DestructedTypeInfo)
02827       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
02828                                                   SecondTypeName.StartLocation);
02829     Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
02830   }
02831   
02832   // Convert the name of the scope type (the type prior to '::') into a type.
02833   TypeSourceInfo *ScopeTypeInfo = 0;
02834   QualType ScopeType;
02835   if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 
02836       FirstTypeName.Identifier) {
02837     if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
02838       TypeTy *T = getTypeName(*FirstTypeName.Identifier, 
02839                               FirstTypeName.StartLocation,
02840                               S, &SS, false, ObjectTypePtrForLookup);
02841       if (!T) {
02842         Diag(FirstTypeName.StartLocation, 
02843              diag::err_pseudo_dtor_destructor_non_type)
02844           << FirstTypeName.Identifier << ObjectType;
02845         
02846         if (isSFINAEContext())
02847           return ExprError();
02848         
02849         // Just drop this type. It's unnecessary anyway.
02850         ScopeType = QualType();
02851       } else
02852         ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
02853     } else {
02854       // Resolve the template-id to a type.
02855       TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
02856       ASTTemplateArgsPtr TemplateArgsPtr(*this,
02857                                          TemplateId->getTemplateArgs(),
02858                                          TemplateId->NumArgs);
02859       TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
02860                                          TemplateId->TemplateNameLoc,
02861                                          TemplateId->LAngleLoc,
02862                                          TemplateArgsPtr,
02863                                          TemplateId->RAngleLoc);
02864       if (T.isInvalid() || !T.get()) {
02865         // Recover by dropping this type.
02866         ScopeType = QualType();
02867       } else
02868         ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);      
02869     }
02870   }
02871       
02872   if (!ScopeType.isNull() && !ScopeTypeInfo)
02873     ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
02874                                                   FirstTypeName.StartLocation);
02875 
02876     
02877   return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
02878                                    ScopeTypeInfo, CCLoc, TildeLoc,
02879                                    Destructed, HasTrailingLParen);
02880 }
02881 
02882 CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp, 
02883                                                 CXXMethodDecl *Method) {
02884   if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0, Method))
02885     assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
02886 
02887   MemberExpr *ME = 
02888       new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, 
02889                                SourceLocation(), Method->getType());
02890   QualType ResultType = Method->getResultType().getNonReferenceType();
02891   MarkDeclarationReferenced(Exp->getLocStart(), Method);
02892   CXXMemberCallExpr *CE =
02893     new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
02894                                     Exp->getLocEnd());
02895   return CE;
02896 }
02897 
02898 Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
02899                                                   QualType Ty,
02900                                                   CastExpr::CastKind Kind,
02901                                                   CXXMethodDecl *Method,
02902                                                   ExprArg Arg) {
02903   Expr *From = Arg.takeAs<Expr>();
02904 
02905   switch (Kind) {
02906   default: assert(0 && "Unhandled cast kind!");
02907   case CastExpr::CK_ConstructorConversion: {
02908     ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
02909     
02910     if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
02911                                 MultiExprArg(*this, (void **)&From, 1),
02912                                 CastLoc, ConstructorArgs))
02913       return ExprError();
02914     
02915     OwningExprResult Result = 
02916       BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 
02917                             move_arg(ConstructorArgs));
02918     if (Result.isInvalid())
02919       return ExprError();
02920     
02921     return MaybeBindToTemporary(Result.takeAs<Expr>());
02922   }
02923 
02924   case CastExpr::CK_UserDefinedConversion: {
02925     assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
02926 
02927     // Create an implicit call expr that calls it.
02928     CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
02929     return MaybeBindToTemporary(CE);
02930   }
02931   }
02932 }    
02933 
02934 Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
02935   Expr *FullExpr = Arg.takeAs<Expr>();
02936   if (FullExpr)
02937     FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
02938 
02939   return Owned(FullExpr);
02940 }