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