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