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