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