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